最长回文字串

来源:互联网 发布:阿里云华北5是哪里 编辑:程序博客网 时间:2024/05/29 07:08

基本思想

将string A用“#”补齐为奇数长度的字符串B,然后构建H数组,将B中的所有回文长度填充进去,最后遍历整个H数组找max, 返回max-1

A: 1223 –> B:#1#2#2#3#
最后时刻H为[1,2,1,2,3,2,1,2,1];

C++实现

#include <iostream>#include <vector>using namespace std;bool check(const string& str){    string _str = str;    reverse(_str.begin(), _str.end());    return _str==str;}//A为所需判断字符串,n为字符串长度int getLongestPalindrome(string A, int n) {    // write code here    int l = 1+2*n;    vector<int> H = vector<int>(l,0);    string B = "#";    for(int i=0; i<n; ++i){        B += A.substr(i,1);        B += "#";    }    cout<<B<<endl;    for(int i=0; i<l; ++i){        int j=0;        int lindex=0;        int rindex=0;        while(1){            lindex = i-j;            rindex = i+j;            if(lindex>=0 && rindex<=l-1){                string _str = B.substr(lindex, (rindex-lindex+1));                if(check(_str)){                    H[i]++;                    j++;                }                else{                    break;                }            }            else{                break;            }        }        for(int j=0; j<l; j++){            if(j==l-1){                cout<<H[j]<<endl;                break;            }            cout<<H[j];        }    }    int max=0;    for(int j=0; j<l; j++){        if(max<H[j])            max=H[j];    }    return max-1;}int main(){    cout<<getLongestPalindrome("1223",4);    //result = 2}
0 0