您的位置:首页 > 其它

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

2016-04-28 11:21 295 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: