Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
题意:实现strstr()函数功能,并返回其字符串的开始匹配下标。
钥匙思路:字符串匹配算法KMP
递推方法求next(j)的值。设已有next(j)= k,则有
0<= k < j 且p0 p1 p2 … pk = pj-k pj-k+1 … pj (1)
又设
next(j + 1) = max{k+ 1 | 0 <= k + 1 < j + 1,使得p0 p1 … pk+1 = pj-k pj-k+1…pj+1成立}(2)
若pk+1 = pj+1,则由(2)知: next(j+1) = k + 1 = next(j) + 1.
若pk+1 != pj+1,则由(1)知模式串在下标k+1处不匹配,因此要在p0-pk进行再次查找匹配前缀与后缀。
p0 p1 p 2 … pk =pk-h pk-h+1 … pk (3)
找到h,则由next(k)的定义知:next(k) = h 结合(1)(3)
p0 p1 … ph = pk-hpk-h+1 … pk = pj-h pj-h+1 … pj
即在p0 p1 p2 … pj-1 pj中找到了长度为h+1的前缀子串与后缀子串。
若ph+1 = pj+1,则由next(j+1)定义知
next(j+1) = h + 1= next(k) + 1 = next(next(j)) + 1
一直递归查找直到 next(t) = -1
public class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() < 1) return 0; //如果模型串为内容为空
if(haystack.length() < 1) return -1; //如果目标串内容为空
int[] next = new int[needle.length()];
int j = 0;
int k = -1;
next[0] = -1;
//next数组
while(j < needle.length() - 1){
if(k == -1 || needle.charAt(j) == needle.charAt(k)){
j++; k++;
next[j] = k;
}else{
k = next[k];
}
}
int haystackidx = 0;
int needleidx = 0;
while(haystackidx < haystack.length() && needleidx < needle.length()){
if(needleidx == -1 || haystack.charAt(haystackidx) == needle.charAt(needleidx)){
haystackidx++; needleidx++;
}else{
needleidx = next[needleidx];
}
}
if(needleidx < needle.length()) return -1;
return haystackidx - needle.length();
}
}