Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
=======================================================
题目链接:https://leetcode.com/problems/implement-strstr/
题目大意:找出haystack中子串needle的最小开始下标,如果没有则返回-1。
思路:KMP算法。
参考代码:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size() , n = needle.size() ;
if ( n == 0 )
return 0 ;
vector <int> next ( n ) ;
getNext ( needle , next ) ;
int i = 0 , j = 0 , index = 0 ;
while ( i < m && j < n )
{
if ( haystack[i] == needle[j] )
{
i ++ ;
j ++ ;
}
else
{
if ( next[j] == -1 )
{
i ++ ;
j = 0 ;
}
else
j = next[j] ;// next[j] = 0,j = 0 和 next[j] >= 1,j = next[j]
}
}
if ( j == n )
return i - n ;
else
return -1 ;
}
private:
void getNext ( string& needle , vector <int>& next )
{
int n = needle.size() , j = 0 , k = -1 ;
next[0] = -1 ;
while ( j + 1 < n )
{
if ( k == -1 || needle[k] == needle[j] )
{
j ++ ;
k ++ ;
if ( needle[k] != needle[j] )
next[j] = k ;
else
next[j] = next[k] ;
}
else
k = next[k] ;
}
}
};