我不懂斑竹beyondyf说的“构造O(N * logN)的DP解法”是什么,自己写了一个程序,看起来挺繁琐。不过也算是能达到题目的要求了。
程序代码:
#include <iostream> #include <string> #include <vector> using namespace std; typedef struct{ int count; string str; }Data_Type; typedef vector<Data_Type>::iterator it; vector<Data_Type> SubStr(string Str)//求子串 { int i, j, k = 1; Data_Type Da; vector<Data_Type> vec; for(i = 2; i <= Str.length(); i ++)//子串的长度 { for(j = 0; j <= Str.length() - i; j ++)//从母串的下标开始 { Da.str = Str.substr(j,i); Da.count = 1; vec.push_back(Da); } } return vec; } vector<Data_Type> Sub_Count(vector<Data_Type>&vec) { vector<Data_Type> Sub; it vec_it1, vec_it2; it Sub_it1; for(vec_it1 = vec.begin(); vec_it1 != vec.end(); vec_it1 ++) { int flag; for(Sub_it1 = Sub.begin(); Sub_it1 != Sub.end(); Sub_it1 ++) { if(vec_it1->str == Sub_it1->str){flag = 0;break;}//当有相同的就马上退出 else flag = 1; } if(flag)//如果在Sub容器中还没有该子串,那么就将它加到Sub容器中。 { Sub.push_back(*vec_it1);//每扫描一个子串就将它加入另一个容器中,然后扫描到下一个子串的时候就跟Sub容器中才子串比较,如果相同,则说明该子串的个数已经计算过 for(vec_it2 = vec_it1 + 1; vec_it2 != vec.end(); vec_it2 ++) if( vec_it1->str == vec_it2->str) (Sub.end()-1)->count ++; } } return Sub; } int main() { string Str; //int k = 1; vector<Data_Type> vec, Sub; it S_it; cout<<"请输入一个字符串:"<<endl; cin>>Str; vec = SubStr(Str); Sub = Sub_Count(vec); Data_Type max, Max;//用来保存出现次数最多的子串 max.count = Sub.begin()->count; max.str = Sub.begin() ->str; for(S_it = Sub.begin(); S_it != Sub.end(); S_it ++) { if(S_it->count > max.count) { max.count = S_it->count; max.str = S_it ->str; } } Max.count = max.count; Max.str = max.str; for(S_it = Sub.begin(); S_it != Sub.end(); S_it ++) { if(S_it->count == Max.count && S_it->str.length() > Max.str.length()) { Max.str = S_it->str; Max.count = S_it->count; } } cout<<"子串个数最多且长度最大的是:"<<Max.str<<endl; return 0; }