KMP模板

来源:互联网 发布:雷电软件儿 编辑:程序博客网 时间:2024/06/16 09:44

改编自白书

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哪些位置出现过*/void find(const std::string& pattern, const std::string& sentence) {    std::vector<int> fail = getFail(pattern);    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()) {            // find a answer            std::cout << i - pattern.length() + 1 << std::endl;            j = fail[j];        }    }}
原创粉丝点击