码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Palindrome Partitioning @ Python

时间:2014-05-29 18:26:15      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

原题地址:https://oj.leetcode.com/problems/palindrome-partitioning/

题意:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

解题思路:回文的分割问题。同样是需要穷举出所有符合条件的集合,那么我们还是使用dfs。

代码:

bubuko.com,布布扣
class Solution:
    # @param s, a string
    # @return a list of lists of string
    def isPalindrome(self, s):
        for i in range(len(s)):
            if s[i] != s[len(s)-1-i]: return False
        return True
    
    def dfs(self, s, stringlist):
        if len(s) == 0: Solution.res.append(stringlist)
        for i in range(1, len(s)+1):
            if self.isPalindrome(s[:i]):
                self.dfs(s[i:], stringlist+[s[:i]])
            
    def partition(self, s):
        Solution.res = []
        self.dfs(s, [])
        return Solution.res
bubuko.com,布布扣

 

[leetcode]Palindrome Partitioning @ Python,布布扣,bubuko.com

[leetcode]Palindrome Partitioning @ Python

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3758437.html

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