本质上就是一个KMP算法的题目,核心就是算出next数组,之后的匹配就简单了。next的算法是在书上找到的。(到处都有)
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int* code = new int[n];
for (int i = 0; i <= n - 1; i++)
{
cin >> code[i];
}
int m;
cin >> m;
int* door = new int[m];
for (int i = 0; i <= m - 1; i++)
{
cin >> door[i];
}
//KMP NEXT
int *next = new int[n];
int k = 0;
next[0] = 0;
for (int i = 1; i <= n - 1; i++)
{
while ((k > 0) && (code[k] != code[i]))
{
k = next[k];
}
if (code[k] == code[i])
{
k++;
}
next[i] = k;
}
//MATCH
int match = 0;
bool succeed = false;
for (int i = 0; i <= m - 1; i++)
{
while (match > 0 && code[match] != door[i])
{
match = next[match];
}
if (code[match] == door[i])
{
match++;
}
if (match == n)
{
cout << i - match + 1 << endl;
succeed = true;
break;
}
}
if(!succeed)
cout << "no solution" << endl;
}
}
LeetCode上的一道题也是类似的,代码放在一起了,上面的代码似乎有些错误,以下面的为准吧:
class Solution {
public:
vector<int> Calnext(string s)
{
int n = s.length();
vector<int> ans(n);
ans[0] = 0;
int k = 0;
for(int i=1;i<n;i++)
{
while(k > 0 && s[k] != s[i])
{
k = ans[k - 1];
}
if(s[k] == s[i])
{
k++;
}
ans[i] = k ;
}
return ans;
}
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if(n==0)return 0;
else if(m==0) return -1;
vector<int> next = Calnext(needle);
int match = 0;
for(int i =0;i<m;i++)
{
while(match > 0 && haystack[i] != needle[match])
{
match = next[match-1];
}
if(haystack[i] == needle[match])
{
match++;
}
if(match == n)
{
return i - match + 1;
}
}
return -1;
}
};