Implement strStr()

標(biāo)簽: C++ 算法 LeetCode 字符串 KMP

每日算法——leetcode系列


問題 Implement strStr()

Difficulty: Easy

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

class Solution {
public:
    int strStr(string haystack, string needle) {
        
    }
};

翻譯

實(shí)現(xiàn)strStr()

難度系數(shù):簡(jiǎn)單

實(shí)現(xiàn)strStr()。
返回匹配時(shí)的第一個(gè)索引, 如果沒有匹配的就返回-1。(感覺原文用針和草堆來(lái)形容帶詼諧)

思路

strstr
經(jīng)典題。

假設(shè):
遍歷到的needle索引為j, haystack索引為i+j, needle,haystack長(zhǎng)度分別為m,n

  • 暴力法
    遍歷haystack和needle,如果haystack[i+j] == needle[j](匹配), 則 j++;
    如果不等于(失配),i++, j = 0 T(O) = m * n
  • KMP
    這個(gè)得專門寫一篇總結(jié)的文章。
    還有Linux的grep, BM算法

代碼

class Solution {
public:
    int strStr(string haystack, string needle) {
        return strStrKMP(haystack, needle);
    }
private:
    // brute-force
    int strStrBF(string haystack, string needle) {
        
        if (needle.empty()){
            return 0;
        }
        int i = 0;
        int hSize =  (int)(haystack.size());
        int nSize = (int)(needle.size());
        if (hSize < nSize){
            return -1;
        }
        while(i < hSize){
            int j = 0;
            if (haystack[i + j] == needle[j]){
                j++;
            }else{
                i++;
                j = 0;
            }
            if (j >= nSize){
                return i;
            }
        }
        return -1;
    }
    
    // KMP
    int strStrKMP(string haystack, string needle) {
        
        if (needle.empty()){
            return 0;
        }
        int i = 0;
        int hSize = static_cast<int>(haystack.size());
        int nSize = static_cast<int>(needle.size());
        if (hSize < nSize){
            return -1;
        }
        vector<int> next(nSize, -1);
        calcNext(needle, next);
        int j = 0;
        while (i < hSize) {
            if (j == -1 || haystack[i] == needle[j]){
                i++;
                j++;
            }else{
                j = next[j];
            }
            if (j >= nSize){
                return i - nSize;
            }
        }
        return -1;
    }
    
    void calcNext(const string& needle, vector<int> &next){
        int nSize = static_cast<int>(needle.size());
        int i = 0;
        int j = -1;
        while (i < nSize - 1) {
            if (j == -1 || needle[i] == needle[j]){
                i++;
                j++;
                next[i] = j;
            }else{
                j = next[j];
            }
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容