Leetcode: Longest Palindromic Substring

原创 2016年08月31日 16:30:22
//初始化dp数组 dp[i][j]=(i>=j)?true:false;
//状态转移方程 dp[i][j] =(s[i]==s[j])? dp[i+1][j-1] : false;
class Solution {
public:
   string longestPalindrome(string s) {
        int n=s.size();
        bool dp[n][n];
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(i>=j){
                    dp[i][j]=true;
                }
                else{
                    dp[i][j]=false;
                }
            }
        }
        int max_=1;
        int start=0;
        for(int j=1;j<n;j++){
            for(int i=0;i<j;i++){
                if(dp[i+1][j-1] && s[i]==s[j]){
                    dp[i][j]=true;
                    if(j-i+1>max_){
                        start=i;
                        max_=j-i+1;
                    }
                }
            }
        }
        return s.substr(start,max_);
    }
};

版权声明:本文为博主原创文章,欢迎指教~

相关文章推荐

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个字)