LeetCode---Longest Palindromic Substring

原创 2015年11月19日 21:10:57

题目大意:给出一个字符串,求出该字符串中的最长回文串。

算法思想:

采用动态规划的解法。利用f(i,j)判断si~sj是否是一个回文串。

状态转移方程 :

  1. f(i,j)=   true  i==j
  2. f(i,j)=   true  s[i]=s[j]   i+1=j;
  3. f(i,j)=  s[i]==s[j]&&f[i-1][j-1];
代码如下:
class Solution {
public:
    string longestPalindrome(string s) {
        int n=s.length();
        bool flag[n][n];//标记数组判定i~j是否为回文串
        int max_len=1;
        int start=0;
        fill_n(&flag[0][0],n*n,false);
        for(int i=0;i<n;++i){
            flag[i][i]=true;
            for(int j=0;j<i;++j){
                flag[j][i]=(s[i]==s[j]&&(i-j<2||flag[j+1][i-1]));
                if(flag[j][i]&&(i-j+1>max_len)){
                    max_len=i-j+1;
                    start=j;
                }
            }
        }
        return s.substr(start,max_len);
    }
};


相关文章推荐

leetcode之路005 Longest Palindromic Substring

#include "stdafx.h" #include #include #include #include using namespace std; class Solution { pu...

leetcode 5: Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum len...

[LeetCode]5 Longest Palindromic Substring(C++,Python实现)

LeetCode OJ的第五题,如果有问题或者给我指点欢迎来信讨论ms08.shiroh@gmail.com 题目描述...

leetcode-5. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt...
  • fao9001
  • fao9001
  • 2017年05月03日 09:08
  • 116

Longest Palindromic Substring(leetcode medium algorithm problem)

本题是LeetCode上的一道中等难度题。 题目是寻找字符串中最长的回文串——原题链接Input: “babad”Output: “bab”Note: “aba” is also a valid a...

LeetCode#5* Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt...

(Leetcode)5. Longest Palindromic Substring(medium)

Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt...

Longest Palindromic Substring(leetcode5)

题目描述: Given a string s, find the longest palindromic substring in s. You may assume that the maxim...

LeetCode OJ:Longest Palindromic Substring

Longest Palindromic Substring   Given a string S, find the longest palindromic substring in S. Yo...

个人记录-LeetCode 5.Longest Palindromic Substring

LeetCode 5
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode---Longest Palindromic Substring
举报原因:
原因补充:

(最多只允许输入30个字)