美文网首页LeetCode
131. 分割回文串

131. 分割回文串

作者: MarcQAQ | 来源:发表于2021-03-07 21:33 被阅读0次

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

令n为s的长度,那我们容易知道一共有2^(n-1)种可能的分割方式,如果采用暴力,对每一种可能我们需要线性时间判断是否是回文。我们可以用动态规划来缩短判断的时间。但由于我们还需要进行一些数组的拼接,字符串的复制操作,采用动态规划可以优化运行时间,但复杂度不会有数量级上的变化,始终是O(n2^n)。考虑空间复杂度,应该为O(n^2)

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        str_len = len(s)
        is_palindrome = [[False] * str_len for _ in range(str_len)]

        # initialise the 2D array
        for idx in range(str_len):
            is_palindrome[idx][idx] = True
            if idx + 1 < str_len:
                is_palindrome[idx][idx + 1] = s[idx] == s[idx + 1]

        # Update the array in such an order
        # 0-2, 1-3, 2-4, ..., n-3-n-1
        # 0-3, 1-4, 2-5, ..., n-4-n-1
        # ...
        # ...
        # 0-n-1
        for length in range(3, str_len + 1):
            for idx in range(0, str_len - length + 1):
                start = idx
                end = idx + length - 1
                is_palindrome[start][end] = is_palindrome[start + 1][end - 1] and s[start] == s[end]

        return self.getPartitionWithMemo(s, 0, is_palindrome)

    
    def getPartitionWithMemo(self, s, cur_idx, is_palindrome):
        if cur_idx == len(s):
            return [[]]

        result = list()
        first_sub_string = ”“
        for end_idx in range(cur_idx, len(s)):
            first_sub_string += s[end_idx]
            # if the first substring is palindrome
            if is_palindrome[cur_idx][end_idx]:
                # recursively get palindrome sub-strings for the rest part
                tmp_results = self.getPartitionWithMemo(s, end_idx + 1, is_palindrome)
                for each in tmp_results:
                    result.append([first_sub_string] + each)

        return result

相关文章

  • LeetCode-131-分割回文串

    LeetCode-131-分割回文串 131. 分割回文串[https://leetcode-cn.com/pro...

  • LeetCode 131-135

    131. 分割回文串[https://leetcode-cn.com/problems/palindrome-pa...

  • 2021.3.7每日一题

    131. 分割回文串[https://leetcode-cn.com/problems/palindrome-pa...

  • leetcode131 分割回文串 golang

    131. 分割回文串[https://leetcode-cn.com/problems/palindrome-pa...

  • 131.分割回文串

    题目描述 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 示例...

  • 131. 分割回文串

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 ...

  • backtracing—— 131. 分割回文串

    这个题是分割回文串,首先回文串的判断,就是设置两个变量,分别从头和尾比较,都一样则是回文串。 然后就是回溯法的思路...

  • LeetCode 131. 分割回文串

    题目 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。回文...

  • dp、dfs:131.分割回文串

    动态规划找出所有回文子串 状态方程式 深度搜索 每次深度回归需注意remove结尾子回文串,防止影响下一组搜索 切...

  • Leetcode 131. 分割回文串(回溯算法 + 子串分割问

    问题描述 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。 示例 ...

网友评论

    本文标题:131. 分割回文串

    本文链接:https://www.haomeiwen.com/subject/rfayqltx.html