【leetcode】Implement strStr()

时间:2023-12-13 09:23:26

Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

最简单的思路,逐一比较:
 class Solution {
public:
int strStr(char *haystack, char *needle) { int n1=strlen(haystack);
int n2=strlen(needle);
int result=-;
bool flag;
for(int i=;i<n1-n2+;i++)
{
flag=true;
for(int j=;j<n2;j++)
{
if(haystack[i+j]==needle[j])
{
continue;
}
else
{
flag=false;
break;
}
} if(flag==true)
{
result=i;
break;
}
}
return result;
}
};
可以采用KMP算法:
KMP算法的核心是,当比较某两个字符不相等时,不必从头开始重新比较,而是根据引入的next,确定子串回溯的位置。
举个例子:
一个子串:
a
b
a
a
b
a
b
a
-1
1
1
2
3
2
next[j]表示了如果在比较字符串时,needle[j]!=haystack[k]
那么下一次比较时,从next[j]所指定的位置进行比较,即j=next[j],k不变
 class Solution {
public:
int strStr(char *haystack, char *needle) { int i=;
int j=;
int n1=strlen(haystack);
int n2=strlen(needle); vector<int> next=getNext(needle); while(i<n1&&j<n2)
{
if(j==-||haystack[i]==needle[j])
{
i++;
j++;
}
else
{
j=next[j];
}
} if(j==n2)
{
return i-j;
}
else
{
return -;
}
} vector<int> getNext(char *needle)
{
int n=strlen(needle); vector<int> next(n);
if(n==)
{
return next;
} next[]=-; int i=;
int k=-;
while(i<n-)
{
if(k==-||needle[k]==needle[i])
{ i++;
k++;
next[i]=k;
}
else
{
k=next[k];
}
} return next; } };
 对于k=next[k]
举个例子:如果比较最
a
b
a
a
b
a
b
a
-1
1
1
2
3
2
最后一个元素的next为2
这是因为,倒数第二个元素与第四个元素不相等,此时
k=next[3]=1;
继续循环,
b==needle[k]=needle[1]
所以
i++
k++
得到
next[7]=2;