首页 > 其他 > 详细

5. Longest Palindromic Substring

时间:2015-04-30 06:18:12      阅读:172      评论: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.

使用dp记录下i到j子串是否为回文。

dp[i][j] = dp[i + 1][j - 1] && (j - i < 2 || c[i] == c[j])

 

public class Solution {
  public String longestPalindrome(String s) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int start = 0;
    int end = 0;
    int length = 0;
    int strLength = s.length();
    boolean[][] dp = new boolean[strLength][strLength];
    for (int j = 0; j < strLength; j++) {
      for (int i = 0; i <= j; i++) {
        char a = s.charAt(i);
        char b = s.charAt(j);
        if (a == b && ((j - i < 2) || dp[i + 1][j - 1])) {
          dp[i][j] = true;
          if (length < j - i + 1) {
            length = j - i + 1;
            start = i;
            end = j;
          }
        }
      }
    }
    return s.substring(start, end + 1);
  }
}

5. Longest Palindromic Substring

原文:http://www.cnblogs.com/shini/p/4467899.html

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