鱼儿慢慢游~~

导航

 

  

题目描述:
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的思想,对应aab, 网上搜到一张

图:

 

依次遍历字符串, step [0, len), 判断s[step:len] 是否问回文子串,  如果是, step +1 继续判断,代码如下:

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        res = []
        self.dfs(s, res, 0, [])
        return res
        
    def dfs(self, s, res, step, cur):
        if step == len(s):
            res.append(list(cur))
            return
        for i in range(step, len(s)):
            if not self.isPar(s[step:i+1]):
                continue
            cur.append(s[step:i+1])
            self.dfs(s, res, i+1, cur)  #注意这里是i+1 不是step+1 ,因为i是上一个子串的末尾, 所以下一次判断从i+1开始的子串进行
            cur.pop()
            
            
    def isPar(self, s):
        l = len(s)
        for i in range(0, l/2):
            if s[i] != s[l-i-1]:
                return False
        return True

 

posted on 2016-08-04 18:04  miss_UU  阅读(201)  评论(0编辑  收藏  举报