Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack.equals(needle) || needle.equals("")) {
return 0;
}
if (haystack == null || needle== null) {
return -1;
}
int si = 0;
int mi = 0;
int[] next = getNextArray(needle);
while (si < haystack.length() && mi < needle.length()) {
if (haystack.charAt(si) == needle.charAt(mi)) {
si++;
mi++;
} else if (next[mi] == -1) {
si++;
} else {
mi = next[mi];
}
}
return mi == needle.length() ? si - mi : -1;
}
private int[] getNextArray(String needle) {
// TODO Auto-generated method stub
if (needle.length() == 1) {
return new int[]{-1};
}
int[] next = new int[needle.length()];
next[0] = -1;
next[1] = 0;
int pos = 2;
int cn = 0;
while (pos < next.length) {
if (needle.charAt(pos-1) == needle.charAt(cn)) {
next[pos++] = ++cn;
} else if (cn > 0) {
cn = next[cn];
} else {
next[pos++] = 0;
}
}
return next;
}
}
本文介绍了一个字符串匹配算法的具体实现,该算法能够高效地找到一个字符串(needle)在另一个字符串(haystack)中首次出现的位置。通过使用getNextArray方法预处理模式串,算法能够在主串中快速搜索模式串。
639

被折叠的 条评论
为什么被折叠?



