Returns the maximum length of a string that matches all characters.

Source: Internet
Author: User
A string contains only three types of letters A, B, and C, such as aabbbcbcaaa. To find the longest string, the length of the longest string must be the same. For example, the eldest son of aabbbcbcaaa is bcbcaa, which contains two types: A, B, and C.


Implement the following C ++ functions:

The following is an O (n) implementation method.



Int getmaxlen (string & SRC)
#include <iostream>#include <string>#include <map>#include <vector>using namespace std;int getMaxLen(string& src){map< vector<int> ,vector<int> > j;//vector<int> k,m;int a_index=0;int b_index=0;int c_index=0;int ba_minus;int ca_minus;vector<int> vo,vo_value;vo.push_back(0);vo.push_back(0);vo_value.push_back(-1);j.insert(make_pair(vo,vo_value));for(int i=0;i<src.length();i++){if (src[i]=='a') a_index++;if (src[i]=='b') b_index++;if (src[i]=='c') c_index++;ba_minus=b_index-a_index;ca_minus=c_index-a_index;vector<int> k;k.clear();k.push_back(ba_minus);k.push_back(ca_minus);map< vector<int> ,vector<int> >::iterator find_flag=j.find(k);if(find_flag!=j.end()){find_flag->second.push_back(i);}else{vector<int> m;m.push_back(i);j.insert(make_pair(k,m));}}map< vector<int>, vector<int> >::iterator bianli=j.begin();int max=0;while(bianli!=j.end()){if(bianli->second.size()>=2){int minus=bianli->second[bianli->second.size()-1]-bianli->second[0];cout<<bianli->second[bianli->second.size()-1]<<endl;cout<<bianli->second[0]<<endl;if(minus>max) max=minus;}bianli++;}return max;}int main(){string test="abcabcabcabc";cout<<getMaxLen(test)<<endl;return 0;}


Returns the maximum length of a string that matches all characters.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.