您的位置:首页 > 编程语言 > Java开发

LeetCode | Implement strStr()

2014-04-03 15:11 375 查看
题目

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
分析
KMP算法

代码

public class ImplementStrStr {
public String strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return null;
}
if (needle.length() == 0) {
return haystack;
}
if (haystack.length() == 0) {
return null;
}
int M = haystack.length();
int N = needle.length();

int[] next = new int
;
next[0] = -1;
int j = 0;
int k = -1;
while (j < N - 1) {
if (k == -1 || needle.charAt(j) == needle.charAt(k)) {
++j;
++k;
next[j] = k;
} else {
k = next[k];
}
}

int i = 0;
j = 0;
while (i < M) {
if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
++i;
++j;
} else {
j = next[j];
}
if (j == N) {
return haystack.substring(i - N);
}
}

return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode java kmp