1. 程式人生 > 其它 >LeetCode_實現 strStr()

LeetCode_實現 strStr()

技術標籤:Leetcode_C

題目:
實現 strStr()
分析:
這裡我用的是暴力迴圈的辦法,
先遍歷haystack字串,找到與needle第一個字元相同的字元位置,然後進入內部迴圈,遍歷needle並一一對比,遇到不同字元跳出;注意這裡需要將i歸位,否則會遺漏字串重疊的情況。在比較完成後需要判斷needle遍歷指標是否與needle長度相同,並以此來判斷師傅符合strstr條件
下面看演算法:

/*
Violence cycle
Finding the first character that matches the needle,
And then it goes into the inner cycle,
go through the needle and compare it to Haystack.
Note:
assigning tag to i when jumping out,
Otherwise, you might miss instances where strings overlap
*/
int strStr(char * haystack, char * needle){ int len = strlen(needle); if(len == 0) return 0; int i=0,j,tag; while(i<strlen(haystack)) { if(haystack[i] == needle[0]) { tag = i; for(j=0;j<len;j++) { if(haystack[
i] == needle[j]) i++; else { i = tag; break; } } if(j == len) return tag; } i++; } return -1; }