算法练习-最长回文子串

练习问题来源

https://wizardforcel.gitbooks.io/the-art-of-programming-by-july/content/01.05.html

要求:

给定一个字符串,求它的最长回文子串的长度。

解法:

这里先给简单的方法,高效的那种还不会。
对于字符串如:accdccbfc,依次在每一个位置ac|cdccbfc acc|dccbfc accd|ccbfc...计算回文长度,最长的就是求的长度。

#include <string>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

// 最长回文子串判断
int LongestPalindrome(const char *s, int n)
{
    int i, j, len = 0, c = 0;
    if(n < 1 || 0 == s)
        return 0;

    for (i = 0; i < n; ++i)
    {
        for (j = 0; (i - j >= 0) && (i + j) < n; ++j) // 判断 acca 这种回文
        {
            if (s[i-j] != s[i+j])
                break;

            c = 2 * j + 1;
        }
        if (len < c)
            len = c;

        for (j = 0; (i - j) >= 0 && (i + j + 1) < n; ++j) // 判断 acbca 这种回文
        {
            if (s[i-j] != s[i+j+1])
                break;

            c = 2 * j + 2;
        }
        if(len < c)
            len = c;
    }

    return len;
}

void main()
{
    char str[128] = {"ImmaIIa"};
    int len = LongestPalindrome(str, 7);
    cout << "the longest palindrome is: " << len << endl;
}
原文地址:https://www.cnblogs.com/nobodyzhou/p/5525391.html