Substring algorithm

后端 未结 11 1477
小蘑菇
小蘑菇 2021-02-11 03:38

Can someone explain to me how to solve the substring problem iteratively?

The problem: given two strings S=S1S2S

11条回答
  •  误落风尘
    2021-02-11 04:07

    A naive algorithm would be to test at each position 0 < in-m of S if Si+1Si+2Si+m=T1T2Tm. For n=7 and m=5:

    i=0:  S1S2S3S4S5S6S7
          | | | | |
          T1T2T3T4T5
    
    i=1:  S1S2S3S4S5S6S7
            | | | | |
            T1T2T3T4T5
    
    i=2:  S1S2S3S4S5S6S7
              | | | | |
              T1T2T3T4T5
    

    The algorithm in pseudo-code:

    // we just need to test if n ≤ m 
    IF n > m:
        // for each offset on that T can start to be substring of S
        FOR i FROM 0 TO n-m:
            // compare every character of T with the corresponding character in S plus the offset
            FOR j FROM 1 TO m:
                // if characters are equal
                IF S[i+j] == T[j]:
                    // if we’re at the end of T, T is a substring of S
                    IF j == m:
                        RETURN true;
                    ENDIF;
                ELSE:
                    BREAK;
                ENDIF;
            ENDFOR;
        ENDFOR;
    ENDIF;
    RETURN false;
    

提交回复
热议问题