题目
我的题解
这道题就是自己写一个indexOf方法。
class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals("")) {
return 0;
}
String h = haystack.replace(needle, "?");
// 如果haustack没有被替换 or needle的长度超过haystack,则找不到
if (h.equals(haystack) || haystack.length() < needle.length()) {
return -1;
}
int j = 0;
int firstIndex;
for (int i = 0; i < haystack.length(); i++) {
// 如果haystack与needle当前字母匹配,则j++
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
} else {
firstIndex = haystack.indexOf(needle.charAt(0), i - j + 1);
firstIndex = (firstIndex > i) ? -1 : firstIndex;
j = (firstIndex == -1) ? 0 : 1;
i = (firstIndex == -1) ? i : firstIndex;
}
// 如果匹配的长度j=needle的长度,则返回索引
if (j == needle.length()) {
return (i - j + 1);
}
}
return -1;
}
}
其他题解
可以用subString方法切块成目标长度,再用equals方法对比。
解法链接
总结
- 倒在不熟悉subString方法上了
- 另外,用多了索引导致有点蒙,做好图解更快捷