题目描述:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
比对字符串haystack和needle,返回haystack中第一次出现needle的位置。
例子:
Example 1:
1 Input: haystack = "hello", needle = "ll" 2 Output: 2
Example 2:
1 Input: haystack = "aaaaa", needle = "bba" 2 Output: -1
解题思路:
这题的思路是很清晰的,把needle的字符串和haystack字符串进行逐个比较。
我的思路是先在haystack中寻找needle的第一个字符,找到后在进行接下来的比较。
代码:
1 int strStr(char* haystack, char* needle) { 2 if(needle[0]=='\0') 3 return 0; 4 bool existFlag=0;//needle是否存在的标志,也是跳出循环的标志 5 int i=0; 6 for(;haystack[i]!='\0';i++){ 7 //先用第一层循环寻找needle的第一个字符 8 if(existFlag==1){ 9 //存在needle直接跳出 10 break; 11 } 12 if(haystack[i]==needle[0]){ 13 int j=0; 14 for(int k=i;haystack[k]!='\0';k++){ 15 //用第二层循环来比对接下的字符串 16 if(needle[j]=='\0'){ 17 //比对成功 18 break; 19 } 20 if(haystack[k]!=needle[j]) 21 //比对失败 22 break; 23 else 24 j++; 25 } 26 if(needle[j]=='\0'){ 27 //考虑到needle在haystack的末尾情况,把existFlag赋值放后面 28 existFlag=1; 29 } 30 } 31 } 32 if(existFlag==0) 33 return -1; 34 else 35 return --i; 36 //因为每次循环结束i都会+1,但跳出设置在循环开头,所以进行-1操作 37 }