题目:给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1
方法一:暴力枚举
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()==0){//如果needle是空,那么不管haystack是什么都返回0
return 0;
}
if(haystack.length()==0){//如果haystack为空,needle不为空,那么返回-1
return -1;
}
int tempLeft = 0;
int tempRight = 0;
int c = 0;//记录左指针匹配以后移动的次数
while(tempRight < needle.length() && tempLeft < haystack.length() ){
if(haystack.charAt(tempLeft)==needle.charAt(tempRight)){//如果匹配,那么右指针++
tempRight++;
c++;
}else{//一旦出现不匹配,右指针归零
tempRight=0;
tempLeft=tempLeft-c;//左指针不匹配后,减掉之前匹配的次数,得到最开始匹配的下标,下面有个++操作,那么就是下一位开始重新匹配
c=0;
}
tempLeft++;
}
if(tempRight!=needle.length()){//如果右指针不等于needle的长度,那么说明循环第一个条件满足,第二个条件不满足肯定不匹配
return -1;
}else{
return tempLeft - tempRight;
}
}
}
方法二:KMP算法
(ps:以后补充,kmp算法现在不太会)