字符串的模式匹配算法——KMP模式匹配算法

字符串的模式匹配算法——KMP模式匹配算法

2023年7月20日发(作者:)

字符串的模式匹配算法——KMP模式匹配算法朴素的模式匹配算法(C++)朴素的模式匹配算法,暴⼒,容易理解#includeusing namespace std;int main(){ string mainStr, str; cin >> mainStr >> str; int i, j, pos = -1, count = 0; for(i = 0; i < (); i++) { for(j = 0; j < (); j++, i++) { if(mainStr[i] != str[j]) { break; } if(j == () - 1) { if(count == 0) { pos = i - j; //记录第⼀个与str相等的字符串在主串mainStr中的第⼀个字母的下标 } count++; //记录与str相等的字符串的数量 } } i = i - j; //对i值(主串指针)进⾏回溯操作 } cout << "pos=" << pos << ",count=" << count << endl; return 0;}KMP模式匹配算法(C++)KMP模式匹配算法相⽐较朴素的模式匹配算法,减少了主串指针回溯的操作#includeusing namespace std;int main(){ string mainStr, str; cin >> mainStr >> str; int i, j, pos = -1, count = 0; int next[256]; //计算next数组的数值 i = 0; j = -1; next[0] = -1; while(i < ()) { if(j == -1 || str[i] == str[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } //查找⼦串的位置和数量 i = 0; j = 0; while(i < ()) { if(mainStr[i] != str[j]) { j = next[j]; } else { if(j == () - 1) { if(count == 0) { pos = i - j; //记录⼦串第⼀次的第⼀个字母出现在主串中的位置 } count++; //记录在主串中含有⼦串的数量 } } i++; j++; } cout << "pos=" << pos << ",count=" << count << endl; return 0;}KMP模式匹配算法改进(C++)改进操作在于计算next数组数值的时候考虑了特殊情况 —— ⼦串形如abcabcabx#includeusing namespace std;int main(){ string mainStr, str; cin >> mainStr >> str; int i, j, pos = -1, count = 0; int next[256]; //计算next数组的数值 i = 0; j = -1; next[0] = -1; while(i < ()) { if(j == -1 || str[i] == str[j]) { i++; j++; if(str[j] == str[i]) { next[i] = next[j]; } else { next[i] = j; } } else { j = next[j]; } } //查找⼦串的位置和数量 i = 0; j = 0; while(i < ()) { if(mainStr[i] != str[j]) { j = next[j]; } else { if(j == () - 1) { if(count == 0) { pos = i - j; //记录⼦串第⼀次的第⼀个字母出现在主串中的位置 } count++; //记录在主串中含有⼦串的数量 } } i++; j++; } cout << "pos=" << pos << ",count=" << count << endl; return 0;}

发布者:admin,转转请注明出处:http://www.yc00.com/web/1689847464a290249.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信