给定字符串 haystack
和 neddle
,在haystack
中找出needle
字符串的出现的第一个位置 ,不存在返回 -1
- 两个指针:
i
,j
i
指向haystack
,j
指向needle
i
和j
同时移动匹配- 若
j
移动到最后一位匹配成功 则返回i
- 若中间任意一位匹配失败,则移动
i
重新从下一位开始匹配
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
//needle全部匹配
if (j == needle.length()) return i;
//已经不可能匹配
if (i +needle.length == haystack.length()) return -1;
//匹配中有不相等的,直接break i++
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}