互为旋转词

来源:互联网 发布:某酒店2000w数据 网盘 编辑:程序博客网 时间:2024/06/15 14:08

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

给定两个字符串AB及他们的长度lenalenb,请返回一个bool值,代表他们是否互为旋转词。

比如:

"cdab",4,"abcd",4

返回:true


思路:将两个相同的字符串A合并出一个字符串,那么如果与字符串B是互为旋转词,A必定包含B。


常规解法:


class Rotation {public:    bool chkRotation(string A, int lena, string B, int lenb) {        if(lena!=lenb)            return false;        string C=A+A;        const char* pC=C.c_str();        const char* pB=B.c_str();        if(NULL==strstr(pC,pB))            return false;        else            return true;             }};


KMP解法:


class Rotation {public:    bool chkRotation(string A, int lena, string B, int lenb) {        if( A.empty() && B.empty() )            return true;        if( A.empty() || B.empty() )            return false;        if( lena != lenb )            return false;        string AB;        AB = A + A;       // return strstr(AB.c_str(),B.c_str())==NULL?false:true;                int flag = KMP(AB,B);        if( flag==1 )            return true;        else            return false;                   }    int KMP(const string s,const string t)    {        int slen,tlen;        int i,j;        int *next = GetNextVal(t,tlen);        //slen = strlen(s);        for( int x = 0; s[x]!='\0'; x++ )        {            slen++;        }        i = 0;        j = 0;        while( i<slen && j<tlen )        {            if( j==-1 || s[i]==t[j] )            {                ++i;                ++j;            }            else            {                j = next[j];            }        }        delete[] next;         if( j==tlen )            return 1;        return 0;    }         int *GetNextVal(const string s,int &len)    {        //len = strlen(s);        for(int x=0; s[x]!='\0'; x++)        {            len++;        }        int *next = new int[len];        int i=0;        int j=-1;        next[0] = -1;        while( i<len-1 )        {            if( j==-1 || s[i]==s[j] )            {                ++i;                ++j;                next[i] = j;            }            else            {                j = next[j];            }        }        return next;    }};






原创粉丝点击