力扣
實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
int strStr(char * haystack, char * needle){
int i = 0;
int j = 0;
int h_len = strlen(haystack);
int n_len = strlen(needle);
while(i<h_len && j<n_len){
if(haystack[i] == needle[j]){
i++;
j++;
}
else{
i = i - j +1;
j = 0;
}
}
if(j == n_len){
return i - j;
}
return -1;
}
KMP算法:
https://subetter.com/algorithm/kmp-algorithm.html
註釋:
例如字符串aababaaba的相同真前綴,真後綴有a和aaba,那麼其中最長的就是aaba