1. 程式人生 > >【死磕演算法】旋轉字串判斷·kmp演算法應用

【死磕演算法】旋轉字串判斷·kmp演算法應用

旋轉字串:

某字串str1的前面任意幾個連續字元移動到str1字串的後面,形成新的字串str2,str2即為str1的旋轉字串。

如“1234”的旋轉字串有“1234”、“2341”、“3412”、“4123”。現給定兩個字串str1,str2,判斷str2是str1的旋轉字串。

思路:

1、首先判斷str1和str2的字串長度是否相等,若不等,返回false;若相等,繼續下一步;

2、如果長度相等,生成str1+str1的大字串;

3、用kmp演算法判斷大字串中是否包含str2。

str1的長度為N,此演算法的時間複雜度為O(N)。

如:

str1 = “1234”,str1+str1 = “12341234”。不難發現,大字串中任意長度為4的子串集合

str1的旋轉詞集合是相等的。

程式碼實現:

class Rotation {
public:
    int next[200];
  
    void getnext(string B, int lenb){
        int i = 0;int j = -1;  next[0] = -1;
        while(i<lenb){
           if(j==-1 || B[i] == B[j]){
            i++;
            j++;
            next[i] = j;
         } 
           else
            j = next[j];
        }
        
    }
    int kmp(string A, int lena, string B, int lenb){
        getnext(B,lenb);
        int i = 0;int j = 0;
        while(i<lena && j<lenb){
           if( j ==-1 || A[i] == B[j]){
            i++;
            j++;
        }
        else
            j = next[j];
        }
      if(j ==lenb)
          return (i-j);
      else
          return -1;
    }
    bool chkRotation(string A, int lena, string B, int lenb) {
        // write code here
        if(lena !=lenb)
            return false;
        string A2 = A+A;
        lena = 2*lena;
        if(kmp(A2,lena,B,lenb)!=-1)
            return true;
        else
            return false;
    }
};