zoukankan      html  css  js  c++  java
  • Leetcode 5——最长回文子串

    先附上代码:

    class Solution {
    public:
        string longestPalindrome(string s) {
        int count = s.size();
        int max = 0;
        string result;
        int j;
        int curlen;
        
        for (int i = 0; i < count; ++i)
        {
            // 如果i为奇数对称
            for (j = 0; (i-j>=0) && (i+j<count); j++)
            {
                if (s[i-j] != s[i+j])
                {
                    break;
                }
    
                curlen = 2 * j + 1;
                if (curlen > max)
                {
                    max = curlen;
                    result = string(s, i-j, max);
                }    
            }
    
            // 如果i为偶数对称
            j = 0;
            for(j = 0; (i-j>=0) && (i+j+1 < count); ++j)
            {
                if (s[i-j] != s[i+j+1])
                {
                    break;
                }
                curlen = 2*j + 2;
                if (curlen > max)
                {
                    max = curlen;
                    result = string(s, i-j, max);
                }
            }
        }
        return result;
        }
    };

    按照书上说的,这种解法叫做中心扩展法,还有一种Manacher算法,有些看不懂,所以,先使用中心扩展法求解最大回文子串。

    分类:区分奇数还是偶数;

    思路:对每个元素进行遍历,将每个元素作为中心点向两边推进,推进的长度设定step,那么子串长度为2*step+2或2*step+1;始终记录最大长度,并保存相应字符串;

  • 相关阅读:
    nvalid bound statement (not found)
    小程序
    maven启动项目时报错
    创建Maven项目出错
    小程序的tab标签实现效果
    C# 异步
    C#中计算时间差
    linq筛选唯一
    GMap.net控件学习记录
    nodepad++ 正则 替换
  • 原文地址:https://www.cnblogs.com/gwzz/p/9200980.html
Copyright © 2011-2022 走看看