题目
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。当needle是空字符串时,返回 0。
示例:
输入: haystack = “hello”, needle = “ll”
输出: 2
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
题解
KMP、BM、Sunday算法等,我都不会(尴尬)。只能遍历字符串一个个匹配了,效率很低。(还得努力啊)
代码
class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty())
return 0;
int hLen = haystack.length();
int nLen = needle.length();
int i = 0, j = 0;
while (i < hLen && j < nLen) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
if (j == nLen) {
return i - j;
}
}
return -1;
}
}