牛客网链接:https://www.nowcoder.com/study/vod/1/1/4
KMP算法讲解---https://blog.youkuaiyun.com/a1b2c3d4123456/article/details/50506454
如果对于一个字符串A,将A的前面任意一部分挪到后边去形成的字符串称为A的旋转词。比如A="12345",A的旋转词有"12345","23451","34512","45123"和"51234"。对于两个字符串A和B,请判断A和B是否互为旋转词。
给定两个字符串A和B及他们的长度lena,lenb,请返回一个bool值,代表他们是否互为旋转词。
测试样例:
"cdab",4,"abcd",4
返回:true
思路:将A连接成A+A,在用KMP算法进行A+A和B的匹配判断,如匹配成功就返回true,若匹配失败就返回false.
C++
#include<iostream>
using namespace std;
bool chkRotation(string A, int lena, string B, int lenb) {
if(lena != lenb)
return false;
string C = A+A;
if(C.find(B)!=string::npos)
return true;
else
return false;
}
int main(){
bool a=chkRotation("1234",14,"2341",14);
cout<<a<<endl;
return 0;
}
java
import java.util.*;
public class Rotation {
public boolean chkRotation(String a, int lena, String b, int lenb) {
if (a == null || b == null || lena != lenb) {
return false;
}
String b2 = b + b;
return getIndexOf(b2, a) != -1;
}
// KMP Algorithm
public int getIndexOf(String s, String m) {
if (s.length() < m.length()) {
return -1;
}
char[] ss = s.toCharArray();
char[] ms = m.toCharArray();
int si = 0;
int mi = 0;
int[] next = getNextArray(ms);
while (si < ss.length && mi < ms.length) {
if (ss[si] == ms[mi]) {
si++;
mi++;
} else if (next[mi] == -1) {
si++;
} else {
mi = next[mi];
}
}
return mi == ms.length ? si - mi : -1;
}
public int[] getNextArray(char[] ms) {
if (ms.length == 1) {
return new int[] { -1 };
}
int[] next = new int[ms.length];
next[0] = -1;
next[1] = 0;
int pos = 2;
int cn = 0;
while (pos < next.length) {
if (ms[pos - 1] == ms[cn]) {
next[pos++] = ++cn;
} else if (cn > 0) {
cn = next[cn];
} else {
next[pos++] = 0;
}
}
return next;
}
}
kmp算法
#include <vector>
#include <string>
#include <iostream>
using namespace std;
//next函数
const vector<int> * kmp_next(string &m) {
static vector<int> next(m.size());
next[0]=0;
int temp;
for(int i=1; i<next.size(); i++) {
temp=next[i-1];
while(m[i]!=m[temp]&&temp>0) {
temp=next[temp-1];
}
if(m[i]==m[temp])
next[i]=temp+1;
else next[i]=0;
}
return &next;
}
//匹配函数
bool kmp_search(string text,string m,int &pos) {
const vector<int> * next=kmp_next(m);
int tp=0;
int mp=0;
for(tp=0; tp<text.size(); tp++) {
while(text[tp]!=m[mp]&&mp)
mp=(*next)[mp-1]; // j=next[j] 不需要回溯了
if(text[tp]==m[mp]) mp++;
if(mp==m.size()) {
pos=tp-mp+1;
return true;
}
}
if(tp==text.size()) return false;
}
int main() {
int pos=0;
kmp_search("ab6666cacbc","ca",pos);
cout<<"position = "<<pos+1<<endl;
return 0;
}
判断两字符串是否互为旋转词的KMP算法

博客介绍判断两字符串是否互为旋转词的方法。若字符串A前面任意部分挪到后边形成的字符串为A的旋转词。思路是将A连接成A+A,用KMP算法进行A+A和B的匹配判断,匹配成功返回true,失败返回false,还给出牛客网及KMP算法讲解链接。
1257

被折叠的 条评论
为什么被折叠?



