1.题目
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
来源:力扣(LeetCode)
链接:实现strStr
2.分析
双指针法:
在字符串中寻找子串,此问题需要将字符串逐个访问,
首先,利用指针1号锁定子串第一个字符在母串中的位置,
然后,通过指针1在母串上滑动,指针1在子串滑动,逐个对比,
当只找到部分子串时,为防止子串中有相同的字符,需要将母串指针返回到第一次找到子串首字符的下一位,继续对比,直至寻找到剩余子串不足以表达目标子串停止,返回-1;
3.代码示例
public static int strStr(String haystack,String needle){
int L = haystack.length(),l = needle.length();
if (l==0){
return 0;
}
int p = 0;
while (p<L-l+1){
while (p<L-l+1 && haystack.charAt(p)!=needle.charAt(0)){
p++;
}
int pp=0,len=0;
while (pp<l && p<L && haystack.charAt(p)==needle.charAt(pp)){
pp++;
p++;
len++;
}
if (len==l){
return p-len;
}else{
p=p-len+1;
}
}
return -1;
}