字符串是否互为旋转

来源:互联网 发布:网络方案 编辑:程序博客网 时间:2024/05/17 09:27

如果对于一个字符串A,将A的前面任意一部分挪到后边去形成的字符串称为A的旋转词。比如A="12345",A的旋转词有"12345","23451","34512","45123"和"51234"。对于两个字符串A和B,请判断A和B是否互为旋转词。


思路:

(1)如果两个字符串长度不等,则肯定不是互为旋转词

(2)令C = A+A,那么如果B是A的旋转词,在A中肯定能找到B。

class Rotation {public:bool chkRotation(string A, int lena, string B, int lenb) {        if(lena != lenb)            return false;         string C = A+A;         if(C.find(B)!=-1)            return true;        else            return false;        }};

当然,这里调用了库函数Find,如果要自己写,则可以使用KMP算法:

class Rotation {public:bool chkRotation(string A, int lena, string B, int lenb) {// write code hereif (lena != lenb)return false;vector<int> next = KMPNEXT(B);string tempAll = A + A;for (int i = 0; i < tempAll.length() - 1 - lenb; ++i){int j ;for ( j = 0; j < lenb ; ++j){if (tempAll[i+j] != B[j]){i += next[j];break;}}if (lenb  == j)return true;}return false;}vector<int>  KMPNEXT(string s){vector<int> temp;temp.push_back(0);int i = 1;while(i < s.length()){int j = temp[i - 1];while(s[i] != s[j] && j != 0)j = temp[j - 1];if (s[i] == s[j])temp.push_back(temp[j] + 1);elsetemp.push_back(0);++i;}return temp;}};


0 0
原创粉丝点击