题目描述:
解题思路:
在haystack中从头开始寻找,然后和needle的首字母比较,不吻合就下一个,吻合就依次向后跳跃一位继续比较,最后输出对应的位置,反之输出-1
代码实现:
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int len = needle.length();
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle.charAt(j)) {
if (j == len - 1) {
return i - j;
}
j++;
}else {
i = i - j;
j = 0;
if (haystack.length() - i < len) {
return -1;
}
}
}
return -1;
}