码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode: Longest Palindromic Substring. java

时间:2014-06-02 09:22:03      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   code   java   a   

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

标签:c   style   class   code   java   a   

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

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