求字符串中对称的子字符串的最大长度

一般方法:

#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;
}

 

posted @ 2014-03-13 23:10  OpenSoucre  阅读(190)  评论(0编辑  收藏  举报