码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - Play with words

时间:2015-03-20 06:45:44      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

Kinda similar with another palindrome DP from LeetCode. Feel it, it is a bottom-up DP - palindrome subsequence.

str = input()
slen = len(str)

dp = [[0 for x in range(slen)] for x in range(slen)] 

for clen in range(1, slen + 1):
    for i in range(0, slen - clen + 1):    
        if clen == 1:
            dp[i][i] = 1
        elif clen == 2:
            dp[i][i + 1] = 2 if str[i] == str[i+1] else 1
        else:
            if str[i] == str[i + clen - 1]:
                dp[i][i + clen - 1] = dp[i + 1][i + clen - 2] + 2
            else:
                dp[i][i + clen - 1] = max(dp[i + 1][i + clen - 2], dp[i + 1][i + clen - 1], dp[i][i + clen - 2])
        #print (str[i:i+clen], dp[i][i + clen - 1])

ret = 1
for i in range(0, slen - 1):    
    len1 = dp[0][i]    
    len2 = dp[i + 1][slen - 1]
    ret = max(ret, len1 * len2)
print (ret)

HackerRank - Play with words

标签:

原文地址:http://www.cnblogs.com/tonix/p/4352541.html

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