求一个字符串中连续出现次数最多的字串

来源:互联网 发布:Mac unlock zip file 编辑:程序博客网 时间:2024/06/08 18:09

此类问题一般用后缀数组解决,不过也可以通过模拟后缀数组来解决。以下是模拟后缀数组的方法

//求一个字符串中连续出现次数最多的子串#include <iostream>#include <string>using namespace std;int main(){string str = "abcabcabcccccdefefefefefef";int len = str.length();int maxCount = 1, count = 1;string longest = "";for (int pos1 = 0; pos1 < len; pos1++){for (int pos2 = pos1+1; pos2 < len; pos2++){count = 1;if (str.substr(pos1, pos2-pos1) == str.substr(pos2, pos2-pos1)){count++;int offset = pos2-pos1;for (int k = pos2+offset; k < len; k+=offset){if (str.substr(pos1, offset) == str.substr(k, offset)){count++;}else{break;}}}if (count > maxCount){maxCount = count;longest = str.substr(pos1, pos2-pos1);}}}cout << longest << ", " << maxCount << endl;}


0 0
原创粉丝点击