求字串中對稱的子字串的最大長度

OpenSoucre發表於2014-03-13

一般方法:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//形如aba
int oneCenter(string const& str, int index){
    int len = 1 , i = 1;
    while((index-i)>=0 && (index+i)< str.length() &&  str[index+i]==str[index-i]){
        len += 2;
        i++;
    }
    return len;
}

//形如abba
int twoCenter(string const& str, int index){
    int len = 0, i = 0;
    while( (index - i) >= 0 && (index+1+i < str.length()) &&  str[index-i] == str[index+1+i]){
        len += 2;
        i ++;
    }
    return len;
}

int solve(string const& str){
    int maxLength = 0;
    for(int i = 0 ; i < str.length(); ++ i){
        maxLength = max(maxLength,max(oneCenter(str,i),twoCenter(str,i)));    
    }
    return maxLength;
}

int main(){
    string str;
    cin >>  str;
    cout<<"Max longest string lenght is  "
        <<solve(str)
        <<endl;
}

 

相關文章