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

131 Palindrome Partitioning

时间:2015-08-05 06:28:54      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

131 Palindrome Partitioning 

这道题先是标识出所有的 s[i:j+1] 是否为 palindrome, 然后在暴力搜索就好

class Solution:
    def __init__(self):
        self.dp = []
        self.ans = []
    
    def partition(self, s):
        LS = len(s)
        dp = [[False] * LS for i in range(0, LS)]
        for ls in range(0, LS):
            for i in range(0, LS-ls):
                if s[i] == s[i+ls] and (ls <= 2 or dp[i+1][i+ls-1]):
                    dp[i][i+ls] = True
        self.dp = dp[:]
        self.help(0, LS, [], s)
        return self.ans

    def help(self, b, e, tmp, s):
        for i in range(b, e):
            if i < e-1 and self.dp[b][i]:
                tmp.append(s[b:i+1])
                self.help(i+1, e, tmp, s)
                tmp.pop()
            if i == e-1 and self.dp[b][i]:
                self.ans.append(tmp+[s[b:i+1]])
                return

 

131 Palindrome Partitioning

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4703577.html

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