您的位置:首页 > 其它

【KMP&字符串匹配】Implement strStr()

2014-04-16 20:50 393 查看
Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法一:简单遍历超时

public class Solution {
public String strStr(String haystack, String needle) {
if(needle == null || haystack == null) return null;

int lenh = haystack.length();
int lenn = needle.length();

String res = null;
for(int i=0; i<lenh; i++){
res = haystack.substring(i, lenh);
if(res.startsWith(needle)) return res;
}
return null;
}
}

解法二:KMP,看懂了,下次又忘了。。。

public class Solution {
public String strStr(String haystack, String needle) {
if(needle == null || haystack == null) return null;

int lenh = haystack.length();
int lenn = needle.length();
if(lenn == 0) return haystack;

int res = kmpFunc(haystack, needle);
if(res == -1) return null;
return haystack.substring(res);

}

public int[] compute(String p){
int m = p.length();
int b[] = new int[m];
b[0] = -1;

int k = -1;
for(int i = 1; i<m; i++){
while(k >= 0 && p.charAt(k+1) != p.charAt(i)){
k = b[k];
}
if(p.charAt(k+1) == p.charAt(i)) k++;

b[i] = k;
}
return b;
}

public int kmpFunc(String t, String p){
int n = t.length();
int m = p.length();
int []next = compute(p);

int q = -1;
for(int i=0; i<n; i++){
while(q>=0 && p.charAt(q+1) != t.charAt(i)){
q = next[q];
}
if(p.charAt(q+1) == t.charAt(i)) q++;
if(q == m-1){
return i-m+1;
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: