zoukankan      html  css  js  c++  java
  • 【leetcode】5. 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.

    思路就是:

      逆置字符串得到新的字符串,记为res。

      在原来的字符串s和res中找最大公共连续子串。(这个不是很会,方法是构建二维数组,如果两个字符相等,等于左上角的值+1)构建出一个如下的二维数组

      

       b  a  b

    c  0  0  0

    a  0  1  0

    b  1  0  2

    a  0  2  0

     

    然后从后扫描最大的数,和其下标,就拿到最大的对角线了。根据下标和对角线的数字,就可以找到最长连续公共子串

    #include<vector>
    #include<string>
    using namespace std;
    
    class Solution {
    public:
        string longestPalindrome(string s) {
            int len=s.length();
            if(len==0||len==1)
                return s;
    
            string res;
            for(int i=len-1;i>=0;i--)
                res+=s[i];
        
            int arr[1000][1000]={0};
    
            for(int i=0;i<len;i++){
                for(int j=0;j<len;j++){
                    if(s[i]==res[j]){
                        if(i==0||j==0)
                            arr[i][j]=1;
                        else arr[i][j]=arr[i-1][j-1]+1;
                    }
                    else arr[i][j]=0;
    
                }
            }
    
            int maxv=0,maxindex=0;
    
            for(int i=len-1;i>=0;i--)
                for(int j=len-1;j>=0;j--){
                    if(arr[i][j]>maxv){
                        maxv=arr[i][j];
                        maxindex=j;}
                }
    
            string ret="";
            for(int i=maxindex;maxv>0;maxv--){
                ret=ret+res[i--];
            }
            return ret;
    
        }
    };

     之前用字符串长度创建二维数组,给memory 超出了,直接int[1000][1000]就ok了,题目里反正讲到最长长度是1000.

     

     

  • 相关阅读:
    新概念英语(1-25)Mrs. Smith's Kitchen
    新概念英语(1-23)Which glasses?
    新概念英语(1-21)Whick book
    BZOJ2212: [Poi2011]Tree Rotations(线段树合并)
    BZOJ4773: 负环(倍增Floyd)
    洛谷P1155 双栈排序(贪心)
    洛谷P1024 一元三次方程求解(数学)
    洛谷P1072 Hankson 的趣味题(数学)
    2018.10.26NOIP模拟赛解题报告
    洛谷P2831 愤怒的小鸟(状压dp)
  • 原文地址:https://www.cnblogs.com/LUO77/p/5718112.html
Copyright © 2011-2022 走看看