求一个字符串中连续出现次数最多的子串
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<vector> #include<iostream> #include<cstdlib> using namespace std; pair<int,string>fun(string str) { vector<string>ss; int len=str.length(); for(int i=0;i<len;i++) ss.push_back(str.substr(i,len-i)); int maxcount=1; string sub; sub=str[0]; for(int i=0;i<len;i++) { for(int j=i+1;j<len;j++) { int count=1; if(ss[i].substr(0,j-i)==ss[j].substr(0,j-i)) { count++; for(int k=j+(j-i);k<len;k+=(j-i)) { if(ss[i].substr(0,j-i)==ss[k].substr(0,j-i)) count++; else break; } if(count>maxcount) { maxcount=count; sub=ss[i].substr(0,j-i); } } } } return make_pair(maxcount,sub); } int main() { string s; while(cin>>s) { pair<int,string>rs; rs=fun(s); cout<<rs.second<<":"<<rs.first<<endl; } }
//输入一个字符串,求出其中出现的相同且长度最长的字符串 #include<iostream> #include<string> #include<cstdlib> #include<stdio.h> using namespace std; int main() { string str,tep; while(cin>>str) { for(int i=str.length()-1;i>1;i--) { for(int j=0;j<str.length();j++) { if(j+i<=str.length()) { size_t t=0; size_t num=0; tep=str.substr(j,i);//从大到小取子串 t=str.find(tep); num=str.rfind(tep); if(t!=num) { cout<<tep<<" "<<t+1<<endl; return 0; } } } } } }
//求全排列问题 #include <iostream> #include <string> using namespace std;
void permute1(string prefix, string str) { if(str.length() == 0) cout << prefix << endl; else { for(int i = 0; i < str.length(); i++) permute1(prefix+str[i], str.substr(0,i)+str.substr(i+1,str.length())); } }
void permute1(string s) { permute1("",s); }
int main(void) { //method1, unable to remove duplicate permutations. permute1("abc"); return 0; }