zoukankan      html  css  js  c++  java
  • 【LeetCode】5. Longest Palindromic Substring

    Longest Palindromic Substring

    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.

    Palindrome Partitioning II 几乎一致,二维数组动态规划问题。

    设置bool数组isPalin

    isPalin[i][j]意为s[i...j]是否为回文字符串。

    因此很容易找到递推关系:当s[i]==s[j]时

    (1)如果i+1==j,或者

    (2)如果isPalin[i-1][j+1]

    那么isPalin[i][j]=true (此时与最大长度longest进行比较,并记录起始位置i)

    否则isPalin[i][j]=false

    提高效率需要注意两点

    1、使用数组比使用vector of vector节省时间;

    2、每次发现当前最长回文串就使用substr取出会耗时间,改成记录开始位置和长度。

    class Solution {
    public:
        string longestPalindrome(string s) {
            if(s == "" || s.size() == 1)
                return s;
            int size = s.size();
            int begin = 0;
            int longest = 1;
            bool isPalin[1000][1000] = {false};
    
            for(int i = 0; i < size; i ++)
                isPalin[i][i] = true;
            for(int i = size-2; i >= 0; i --)
            {//isPalin[size-1][size-1] has set to true
                for(int j = i+1; j < size; j ++)
                {//isPalin[i][i] has set to true
                    //check whether s[i...j] is a palindrome
                    if(s[i] == s[j])
                    {
                        if(j == i+1 || isPalin[i+1][j-1])
                        {//case1: j is next to i
                         //case2: s[i+1...j-1] is a palindrome
                            isPalin[i][j] = true;
                            if(j-i+1 > longest)
                            {
                                longest = j-i+1;
                                begin = i;
                            }
                        }
                    }
                }
            }
            return s.substr(begin, longest);
        }
    };

  • 相关阅读:
    Photon3Unity3D.dll 解析三——OperationRequest、OperationResponse
    关于VS2010的一些操作
    Photon3Unity3D.dll 解析二——EventData
    Photon3Unity3D.dll 解析一
    关于U3D中的移动和旋转
    U3D的一些常用基础脚本
    U3D模拟仿真实现
    构建基于TCP的应用层通信模型
    TCP协议的三次握手
    Python生成随机字符串
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4179251.html
Copyright © 2011-2022 走看看