java提供的indexOf()方法能直接找到子串首字符在字符串中的位置,本题直接return haystack.indexOf(needle);即可(见第4段代码)
/**
* 自己的代码
* 虽然前面6行做特殊处理使得代码不太精简,但是能让代码效率高一些
* Runtime: 1 ms, faster than 59.23%
* Memory Usage: 38.7 MB, less than 33.67%
*/
class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals(""))
return 0;
if (haystack.length() < needle.length())
return -1;
char[] hArray = haystack.toCharArray();
char[] nArray = needle.toCharArray();
for (int i = 0; i <= hArray.length - nArray.length; i++) {
int j = 0;
while (hArray[i + j] == nArray[j])
if (++j == nArray.length)
return i;
}
return -1;
}
}
/**
* discuss中的elegant代码
* 代码很优美,但很低效
* 和我的思路一样,只是没有做特殊情况处理的提前判断处理、没有将string转换为charArray
* Runtime: 9 ms, faster than 11.64%
* Memory Usage: 39.1 MB, less than 10.61%
*/
class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) // 上一次的比较结果是否达到了needle的最后一位
return i;
if (i + j == haystack.length())
return -1;
if (haystack.charAt(i + j) != needle.charAt(j))
break;
}
}
}
}
/**
* 用substring()方法比较needle和haystack的部分子串是否相同
* 这个方法最快,代码也最精简,就是不知道面试题能不能用substring()方法
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 38.8 MB, less than 29.96%
*/
class Solution {
public int strStr(String haystack, String needle) {
int l1 = haystack.length(), l2 = needle.length();
for (int i = 0; i <= l1 - l2; i++)
if (haystack.substring(i, i + l2).equals(needle))
return i;
return -1;
}
}
/**
* java提供的indexOf()方法能直接找到子串首字符在字符串中的位置,当然该题不能直接用
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 39.3 MB, less than 5.07%
*/
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
/**
* kmp算法,时间复杂度O(mn)
* Runtime: 2 ms, faster than 47.30%
* Memory Usage: 38.7 MB, less than 34.40%
*/
class Solution {
public int strStr(String haystack, String needle) {
char[] hArray = haystack.toCharArray();
char[] nArray = needle.toCharArray();
int[] next = getNext(nArray);
int i = 0, j = 0;
for (; i < hArray.length && j < nArray.length; i++) {
while (j > 0 && hArray[i] != nArray[j])
j = next[j - 1];
if (hArray[i] == nArray[j])
j++;
}
return j == nArray.length ? i - j : -1;
}
// 计算next数组
private int[] getNext(char[] nArray) {
int[] next = new int[nArray.length];
for (int i = 1, j = 0; i < nArray.length; i++) {
while (j > 0 && nArray[i] != nArray[j])
j = next[j - 1];
if (nArray[i] == nArray[j])
j++;
next[i] = j;
}
return next;
}
}