[LeetCode] Longest Palindromic Substring 解题报告

来源:互联网 发布:淘宝创业成功故事 编辑:程序博客网 时间:2024/05/17 04:37

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></div>

0 0