28. Implement strStr()

1.問題

  • 實作strStr, 若找不到則回傳 -1

2.想法

  • 提問

  • function header, parameter

  • test input

  • 說明想法

    • 當碰到相同字母時, 讓計數器增加

    • 當不同字母時, 索引值就是減去計數器

  • 測試計算複雜度: O(n)

3.程式碼

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (haystack.empty() && needle.empty()) {
            return 0;
        }
        if (haystack.empty()) {
            return -1;
        }
        if (needle.empty()) {
            return 0;
        }
        
        int s1 = haystack.length(), s2 = needle.length();
        for (int i = 0; i < s1; i++) {
            if (haystack[i] = needle[0] &&
                haystack.substr(i, s2) == needle) {
                return i;
            }
        }
        
        return -1;
    }
};

Last updated