最长回文字串

基本思想

将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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值