字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。
示例1:
输入:s1 = "waterbottle", s2 = "erbottlewat"
输出:True
示例2:
输入:s1 = "aa", s2 = "aba"
输出:False
提示:
字符串长度在[0, 100000]范围内。
说明:
你能只调用一次检查子串的方法吗?
手撕kmp:
- class Solution {
- public:
- int ne[100005];
- bool isFlipedString(string s1, string s2) {
- if(s1.size() != s2.size() ) return false;
- if(s1 == s2) return true;
- int n = s1.size();
- s1 =" "+ s1+s1;
- s2 = " "+s2;
- //计算next数组
- for(int i = 2 , j = 0; i <= n ; i++)
- {
- while( j && s2[i] != s2[j+1] ) j = ne[j];
- if(s2[i] == s2[j+1]) j++ ;
- ne[i] = j;
- }
- //开始匹配
- for(int i = 1 , j = 0 ; i <= 2*n ;i++)
- {
- while( j && s1[i] != s2[j+1]) j = ne[j];
- if( s1[i] == s2[j+1]) j++;
- if( j == n) {
- j=ne[j];
- return true;
- }
- }
- // if( s1.find(s2) != string::npos) return true; //匹配失败返回-1 也能写做string::npos
- return false;
- }
- };
- //官方题解:搜索自字符串
- class Solution {
- public:
- bool isFlipedString(string s1, string s2) {
- return s1.size() == s2.size() && (s1 + s1).find(s2) != string::npos;
- }
- };