Sunday, March 3, 2013
[LeetCode] Implement strStr()
Thought:
This is a KMP algorithm. KMP
Code:
public class Solution {
public String strStr(String haystack, String needle) {
if (needle.length() == 0) return haystack;
int[] P = generate(needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while ((j > 0) && (needle.charAt(j) != haystack.charAt(i))) j = P[j - 1];
if (needle.charAt(j) == haystack.charAt(i)) j++;
if (j == needle.length()) return haystack.substring(i - needle.length() + 1);
}
return null;
}
public int[] generate(String s) {
int[] p = new int[s.length()];
int j = 0;
for (int i = 1; i < s.length(); i++) {
while ((j > 0) && s.charAt(j) != s.charAt(i)) j = p[j - 1];
if (s.charAt(j) == s.charAt(i)) {
j++;
p[i] = j;
}
}
return p;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment