[Leetcode] Implement strStr()
Implemet strStr()
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack
暴力匹配算法 回溯主串 i = i-j +1;
j = 0;
class Solution {
public:
int strStr(string haystack, string needle) {
int i=0; int j=0;
while(i < haystack.size() && j < needle.size()) {
if (haystack[i] == needle[j]) {
++i; ++j;
} else {
i =i -j + 1;
j = 0;
}
}
return j != needle.size() ? -1 : i - j;
}
};
KMP 算法 不回溯 主串 i 一直走
class Solution{
public:
void getNext(string pat , vector<int>&next){
int i =0 , j=-1;
next[0]=-1;
while( i != pat.size())
{
while( j !=-1 && pat[i] != pat[j]) j = next[j] ;
++i;++j;
next[i] = j;
}
}
int strStr(string haystack , string needle)
{
int i = 0, j=0;
vector<int>next(needle.size()+1) ;
getNext(needle, next);
while( i != haystack.size())
{
while( j !=-1 && haystack[i] != needle[j]) j = next[j] ;
++i; ++j;
if(j == needle.size()) return i-j;
}
return -1;
}
}
上面的是通常用的KMP算法,但是算法是有一定缺陷的。比如我们的模式串 pattern =“AAAAB”,其中很容易得到next数组为01230。如果目标匹配串为 “AAAACAAAAB” ,大家可以模拟一下,A要回溯多次。就是说我们的next数组优化并不彻底。优化算法:next[i]表示匹配串在i处如果匹配失败下次移到的位置。下面是优化后的的求next数组的代码。虽然两种写求得next值不一样但是kmp函数的写法是一样的。
class Solution {
public:
void getNext(string needle, vector<int> & next){
int i = 0, j = -1;
next[i] = j ;
while( i ! = needle.size())
{
while( j !=-1 && needle[i] == needle[ j]) j = next[j]
++ i ; ++ j;
// 特殊情况, 这里即为优化之处,考虑 AAAAAB, 防止4个A 形成 0123 在匹配时多次迭代。
if( needle[i ] == needle[j]) next[i] = next[j] ;
else next[i ] = j;
}
}
int strStr (string haystack , string needle) {
if(haystack.empty()) return needle.empty() ? 0 :-1;
if(needle.empty()) return 0 ; // 空子串
vector<int > next (needle.size()+1) ;
getNext(needle , next) ;
int i =0 , j =-1 ;
while(i != haystack.size() )
{
while( j!= -1 && haystack[i] != needle[j]) j = next[j];
++i ; ++j ;
if(j == needle.size()) return i-j;
}
return -1;
}
};

浙公网安备 33010602011771号