KMP模板

改編自白書

std::vector<int> getFail(const std::string& str) {
    std::vector<int> fail(str.length() + 1, 0); 
    for (int i = 1; i < str.length(); i++) {
        int j = fail[i];
        while (j > 0 && str[j] != str[i])
            j = fail[j];
        fail[i + 1] = str[i] == str[j] ? j + 1 : 0;
    }   
    return fail;
}

/*
求:pattern在sentence哪些位置出現過
*/
std::vector<int> find(const std::string& pattern, const std::string& sentence) {
    std::vector<int> fail = getFail(pattern), ret;
    int j = 0;
    for (int i = 0; i < sentence.length(); i++) {
        while (j > 0 && pattern[j] != sentence[i])
            j = fail[j];
        if (pattern[j] == sentence[i])
            j++;
        if (j == pattern.length()) {
            ret.push_back(i - pattern.length() + 1); 
            j = fail[j];
        }   
    }   
    return ret;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章