码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2015-04-03 17:06:38      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

  动态规划

我的代码:

技术分享
public class Solution {
    public String longestPalindrome(String s) {
        if(s == null || s.length() == 0) return s;
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        int start = 0;
        int max = 1;
        for(int i = 0; i < len; i++)
        {
            dp[i][i] = true;
            if(i < len- 1 && s.charAt(i) == s.charAt(i+1))
            {
                max = 2;
                start = i;
                dp[i][i+1] = true;
            }
        }
        for(int size = 3; size <= len; size++)
        {
            for(int i = 0; i <= len-size; i++)
            {
                int j = i+size-1;
                if(dp[i+1][j-1] && s.charAt(i)==s.charAt(j))
                {
                    max = size;
                    start = i;
                    dp[i][j] = true;
                }
            }
        }
        return s.substring(start,start+max);
    }
}
View Code

学习之处:

  • 动归方程为dp[i][j] = (s.charAt(i) == s.charAt(j)) && dp[i+1][j-1] ? true : false;
  • 想不出来动态规划的方程,就先想的dfs怎么做,然后再反向思维得出动态规划的方程,动态规划之所以快,是因为减少了好多的重复计算。

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4390429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!