首页 > 编程语言 > 详细

Leetcode: Longest Palindromic Substring. java

时间:2014-06-02 09:21:10      阅读:336      评论:0      收藏:0      [点我收藏+]

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 "";
        int n = s.length();
        int max = 0, start = 0, end = 0;
        boolean[][] c = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                c[i][j] = i >= j ? true : false;
            }
        }
        //c[i][j] 记录从第i个到第j个是不是回文。
        for (int j = 1; j < n; j++) {
            for (int i = 0; i < j; i++) {
                if (s.charAt(i) == s.charAt(j) && c[i+1][j-1]) {
                    c[i][j] = true;
                    if (j - i + 1 > max) {
                        max = j - i + 1;
                        start = i;
                        end = j;
                    }
                }
                else
                    c[i][j] = false;
            }
        }
        return s.substring(start, end+1);
    }
}

Leetcode: Longest Palindromic Substring. java,布布扣,bubuko.com

Leetcode: Longest Palindromic Substring. java

原文:http://www.cnblogs.com/mengfanrong/p/3763497.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!