[LeetCode] Longest Palindromic Substring 解题报告

REF: http://fisherlei.blogspot.com/2012/12/leetcode-longest-palindromic-substring.html

DP solution

定义函数
P[i,j] = 字符串区间[i,j]是否为palindrome.

首先找个例子,比如S="abccb",
    S=    a  b  c  c  b
Index = 0  1  2  3  4

P[0,0] =1  //each char is a palindrome
P[0,1] =S[0] == S[1]    , P[1,1] =1 
P[0,2] = S[0] == S[2] && P[1,1], P[1,2] = S[1] == S[2] , P[2,2] = 1
P[0,3] = S[0] == S[3] && P[1,2], P[1,3] = S[1] == S[3] && P[2,2] , P[2,3] =S[2] ==S[3],  P[3,3]=1       
......................
由此就可以推导出规律

P[i,j] = 1  if i ==j
        =  S[i] ==S[j]   if j = i+1

        =  S[i] == S[j] && P[i+1][j-1]  if j>i+1

代码如下所示:

<div>
public class Solution {
    public String longestPalindrome(String s) {
        if (s == null) {
            return null;
        }
        
        int len = s.length();
        if (len == 0) {
            return "";
        }
        
        int max = 0;
        int rets = 0; // record the solution start
        int rete = 0; // record the solution end
        
        // ref: http://fisherlei.blogspot.com/2012/12/leetcode-longest-palindromic-substring.html
        boolean isP[][] = new boolean[len][len];
        for (int end = 0; end < len; end++) {
            for (int start = 0; start <= end; start++) {
                if (start == end) {
                    isP[start][end] = true; 
                } else {
                    // 1: start == end - 1, true if s.charAt[start] == s.charAt[end]
                    // 2: start < end - 1, true if s.charAt[start] == s.charAt[end] && isP[start + 1][end - 1])
                    isP[start][end] = s.charAt(start) == s.charAt(end) && 
                        (start == end - 1 || isP[start + 1][end - 1]);
                }
                
                if (isP[start][end] && max < end - start + 1) {
                    max = end - start + 1;
                    rets = start;
                    rete = end;
                }
            }
        }
        
        return s.substring(rets, rete + 1);
    }
}
</div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值