程序员面试宝典字符串中连续出现次数最多的子串

来源:互联网 发布:windows外观设置 编辑:程序博客网 时间:2024/06/08 15:18

题目:求解字符串中连续出现次数最多的子串,如abcbcbcbcab,则bc连续出现次数最多为4次

#include <iostream>#include <string>using namespace std;//比较子串和在字符串中出现与其同一首字符的子串是否相等bool strmatch(string temp,int len,string str,int k){int count=0;for (int i=0;i<len&&k<str.size();++i,++k){if (temp.at(i)==str.at(k)){++count;}}if (count==len){return true;}else{return false;}}void maxcount(string str){if (str.size()==0){return;}int len=str.size();int count=1;int maxcount=1;string longstr;bool ismatch=false;//子串的长度由高到低for (int i=len-1;i>=1;--i){for (int j=0;j<len;++j){if (i+j<=len){//获取从j开始的长度为i的子串string temp=str.substr(j,i);for (int k=j+i;k<len;k=k+i){//当首字符相等时才比较,否则breakif (temp.at(0)==str.at(k)){ismatch=strmatch(temp,i,str,k);if (ismatch==true){++count;}}else{break;}}if (maxcount<count){maxcount=count;longstr=temp;}count=1;}}}cout<<maxcount<<endl;cout<<longstr<<endl;}int main(){string str="abcbcbcbcabc";maxcount(str);getchar();return 0;}


0 0
原创粉丝点击