1. 程式人生 > >LeetCode 28. 實現strStr() Implement strStr()(C語言)

LeetCode 28. 實現strStr() Implement strStr()(C語言)

題目描述:

實現 strStr() 函式。
給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。

示例 1:

輸入: haystack = “hello”, needle = “ll”
輸出: 2

示例 2:

輸入: haystack = “aaaaa”, needle = “bba”
輸出: -1

說明:

當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

題目解答:

方法1:暴力解法(雙指標)

對於長串的每一個位置,判斷其後是否與短串匹配。相當於雙指標,一個記錄長串遍歷到的位置,一個記錄短串遍歷到的位置。
執行時間0ms,程式碼如下。

bool comp(char* s1, char* s2) {
    while(*s2) {
        if(*s2 != *s1)
            return false;
        s1++;
        s2++;
    }
    return true;
}
int strStr(char* haystack, char* needle) {
    int
len1 = strlen(haystack), len2 = strlen(needle); if(len2 == 0) return 0; int i = 0; for(i = 0; i + len2 <= len1; i++) { if(comp(haystack + i, needle)) return i; } return -1; }

方法2:KMP演算法

還沒看,等看完再回來寫。。。