码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2015-01-27 15:02:38      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

#include<iostream>
#include<string.h>
using namespace std;

string longestPalindrome(string s) {
    int len = s.size();
    int newlen = len * 2 + 1;
    char str[newlen];
    int p[newlen];
    int i, j, k, r, id;
    int maxr = 0;
    str[0] = '#';
    for(i = 1, j = 0 ;s[j] != '\0'; i++, j++) {
        str[i] = s[j];
        str[++i] = '#';
    }    
    str[i] = '\0';

    p[0] = 1;
    for(i = 1, r = 1, id = 0; i < newlen; i++) {
        if(r > i) p[i] = (p[id * 2 - i] < (r - i))?p[id * 2 - i]:(r - i);
        else p[i] = 1;
        while(str[i + p[i]] != '\0' && str[i + p[i]] == str[i - p[i]])  p[i]++;  
        if(p[i] >= maxr) {
            maxr = p[i];
            id = i;
            r = i + p[i] - 1;
        }
    }
    string str1 = s.substr((id - maxr + 1) / 2, maxr - 1);
    return str1;
}

int main() {
    string str1 = longestPalindrome("c");
    cout << str1 << endl;
}


Longest Palindromic Substring

标签:

原文地址:http://blog.csdn.net/uj_mosquito/article/details/43194021

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!