问题:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
问题要求:若目标字符串是当前字符串的子串时,返回目标串首次出现的下标;否则返回-1.
代码示例:
1、
这个问题是比较简单的,直接暴力解法即可。
不断调整起始位置,判断是否和目标串相等。
73个tests, 平均时间大概为7ms。
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
for (int i = 0; i <= haystack.length() - needle.length(); ++i) {
if (haystack.substring(i, i + needle.length()).equals(needle)) {
return i;
}
}
return -1;
}
}
2、
考虑到暴力解法可能不是最优的,于是用Java现成的接口测试了一下。
发现73个tests, 平均时间大概为8ms。
个人感觉还是与测试用例有关。
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
return haystack.indexOf(needle);
}
}
3、
这个是看String.indexOf源码后,仿照实现的。
indexOf的本质仍是暴力解法,只不过将String换成char数组,然后逐个比对。
73个tests,平均耗时7ms
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
//return haystack.indexOf(needle);
int nLen = needle.length();
if (nLen == 0) {
return 0;
}
int hLen = haystack.length();
char[] hChars = haystack.toCharArray();
char[] nChars = needle.toCharArray();
int hIndex = 0;
while (hIndex <= hLen - nLen) {
//hIndex首先找到第一个相等的位置
while (hIndex <= hLen - nLen && hChars[hIndex] != nChars[0]) {
++hIndex;
}
if (hIndex > hLen - nLen) {
return -1;
}
//若找到第一个匹配的位置,则比较后续char
int nIndex = 1;
for (int j = hIndex + 1; nIndex < nLen; ) {
if (hChars[j] == nChars[nIndex]) {
++j;
++nIndex;
} else {
break;
}
}
if (nIndex == nLen) {
//完全匹配
return hIndex;
}
//进行下次匹配
++hIndex;
}
return -1;
}
}
4、考虑KMP算法
class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
char[] source = haystack.toCharArray();
char[] pattern = needle.toCharArray();
int[] next = getNext(pattern);
int i = 0;
int j = 0;
while (i < source.length && j < pattern.length) {
if (j == -1 || source[i] == pattern[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if (j == pattern.length) {
return i - j;
} else {
return -1;
}
}
private int[] getNext(char[] pattern) {
int[] next = new int[pattern.length];
next[0] = -1;
int i = 0;
int j = -1;
while (i < pattern.length - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
++i;
++j;
next[i] = j;
} else {
j = next[j];
}
}
return next;
}
}
KMP解释的比较好的,可以参考:
转自知乎-我见过最通俗易懂的KMP算法详解