题目描述:给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
思路1、KMP算法
思路2、substring字串来替换下,一个一个检测。
class Solution {
public int strStr(String haystack, String needle) {
class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
// 先检查一下 haystack 剩下的长度是否足够提供 needle 的长度
if (i + needle.length() <= haystack.length()) {
String x = haystack.substring(i, i + needle.length());
if (x.equals(needle)) {
return i;
}
}
}
return -1;
}
}
return -1;在return 0;处,它应该返回-1而不是0。
如果 needle 为空字符串,则函数是合法的且返回 0。
但是如果 needle 不为空并且无法在 haystack 中找到,那么函数应该返回 -1 而不是 0,
来明确指出未找到对应的子字符串
}
}