字符串是否互为旋转

如果对于一个字符串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 here
			if (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);
				else
					temp.push_back(0);
				++i;
			}
			return temp;
		}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值