判断A是不是B的旋转字符串的3种方法

来源:互联网 发布:最完美网络架构图 编辑:程序博客网 时间:2024/05/22 05:02
class Rotation {public:    bool chkRotation(string A, int lena, string B, int lenb) {        // write code here        if(lena != lenb)            return true;        string C;        C = A + A;        if(C.find(B,0) != -1)            return true;        return false;    }};

class Rotation {public:    bool chkRotation(string A, int lena, string B, int lenb) {        // write code here        if(lena != lenb)            return false;        string C = A + A;        for(int i = 0; i < lena + lena;i++){            if(C.substr(i,lenb) == B)                return true;        }        return false;    }}

kmp匹配

class Rotation {public:    bool chkRotation(string A, int lena, string B, int lenb) {        // write code here        if(lena != lenb)            return false;        string C = A + A;       int next[lenb];//        int *next = new int[lenb];        return kmp(C,B,next);    }        void makeNext(string B,int next[]){            next[0] = 0;            int k = 0;            for(unsigned int i = 1; i < B.size();i++){                while(k > 0 && B[i] != B[k])                    k = next[k -1];                if(B[i] == B[k])                    ++k;                next[i] = k;            }       }                 bool kmp(string C,string B,int next[]){            makeNext(B,next);           unsigned int lengthOfCompare = 0;            for(unsigned int i = 0; i < C.size(); ++i){                while(lengthOfCompare > 0 && C[i] != B[lengthOfCompare])                    lengthOfCompare = next[lengthOfCompare - 1];                if(B[lengthOfCompare] == C[i])                    ++lengthOfCompare;                if(lengthOfCompare == B.size())                    return true;            }            return false;        }};


0 0
原创粉丝点击