字符串匹配算法(KMP算法)

力扣
實現 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章