[Leetcode] 131. Palindrome Partitioning 分割字符串

131. Palindrome Partitioning (题目链接)

Medium

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

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

方法1:

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        rlt = []
        def isPalindrome(s: str):
            return s == s[::-1]
        
        def dfs(start: int, partitions: List[str]):
            if start == len(s):
                rlt.append(copy.deepcopy(partitions))
                return
            for i in range(start, len(s)):
                if isPalindrome(s[start: i + 1]):
                    partitions.append(s[start:i + 1])
                    dfs(i + 1, partitions)
                    partitions.pop()
                    
        dfs(0, [])
        return rlt

方法2:对方法1进行优化

因为我们在判断是否是回文的时候,会判断很多重复的字符串是否是回文,我们用动态规划记录下所有用到的可能的字符串是否是回文

其实就是利用了[LeeCode] 5. Longest Palindromic Substring

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        rlt = []
        dp = [[False] * len(s) for i in range(len(s))]
        for j in range(len(s)):
            for i in range(j + 1):
                if i == j:
                    dp[i][j] = True
                elif j - 1 == i:
                    dp[i][j] = s[i] == s[j]
                else:
                    dp[i][j] = dp[i + 1][j - 1] and s[i] == s[j]

        def dfs(start: int, partitions: List[str]):
            if start == len(s):
                rlt.append(copy.deepcopy(partitions))
                return
            for i in range(start, len(s)):
                if dp[start][i]:
                    partitions.append(s[start:i + 1])
                    dfs(i + 1, partitions)
                    partitions.pop()

        dfs(0, [])
        return rlt

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值