class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
vector<int> ne(m+1);//这里容易写错,这个是小括号;
if(m == 0 ) return 0;
ne[0] = -1;//不要忘了,如果找不到相等的前后缀,就令 next[i] = -1
for(int i = 1, j = -1; i < m ; i ++)//求next数组的时候,i从1开始, 切记
{
while(j != - 1&& needle[i] != needle[j +1]) j = ne[j];//回头找
if(needle[i] == needle[j + 1])
{
j ++;//匹配之后, 往前走
}
ne[i] = j;//标记
}
for(int i = 0 , j = -1 ; i < n ; i ++)
//匹配过程, 下标从1开始;n 模板串长度
{
while(j != -1 && haystack[i] != needle[j + 1])
j = ne[j];
if(haystack[i]==needle[j + 1])
j ++;
if(j == m-1)//匹配成功, 就是长度等于匹配串的长度 , 是j =
{
return i -j ;//j是起始长度
//如果不直接返回, j = ne[j],寻找下一个妹子
}
}
return -1;
}
};
函数法…
只能找到第一个元素的起始下标
class Solution {
public:
int strStr(string s, string p) {
return s.find(p);
}
};
我的leetcode从今天开始刷了,Devc如何调试
#include <bits/stdc++.h>
using namespace std;
//直接粘贴
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.length(), m = needle.length();
if (m == 0)
return 0;
vector<int> next(m);
next[0] = -1;
int j = -1;
for (int i = 1; i < m; i++) {
while (j > -1 && needle[i] != needle[j + 1]) j = next[j];
if (needle[i] == needle[j + 1]) j++;
next[i] = j;
}
j = -1;
for (int i = 0; i < n; i++) {
while (j > -1 && haystack[i] != needle[j + 1]) j = next[j];
if (haystack[i] == needle[j + 1]) j++;
if (j == m - 1)
return i - m + 1;
}
return -1;
}
};
//自己写参数还是要自己传入的
int main(){
Solution m;
cout << m.strStr("sadbutsad", "sad") << endl;
//定义类.方法(参数,参数);
}