题目来源于力扣–https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnr003/
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
采用双指针法,分别指向两个数组的首位,如果两个元素相等,指针同时后移,如果不相等,needle从首位重新开始,haystack从相同元素的刚开始相同位置的下一个位置开始,循环终止条件,两个数组有一个数组为空就截止,如果needle为空说明找到了,如果两个数组同时为空,说明两个数组元素相同,如果只有haystack为空,说明没有找到。
main函数代码
#include<stdio.h>
int strStr(char * haystack, char * needle);
int main(){
char haystack[] = "ab";
char needle[] = "ba";
int pos = strStr(haystack,needle);
printf("%d",pos);
return 0;
}
strStr()函数
int strStr(char * haystack, char * needle){
// 如果为空返回0
if(needle[0]=='\0'){
return 0;
}
// 双指针指向数组首位
int i = 0;
int j = 0;
while(haystack[i]&&needle[j]){
// 两个元素相同指针后移
if(haystack[i]==needle[j]){
i++;
j++;
}else{
// 第一个相同元素的下一个位置
i=i-j+1;
// 从头开始
j=0;
}
}
// 如果为空说明找到了
if(!needle[j]){
// 返回第一个相同的位置
return i-j;
}
return -1;
}