leetcode 面试题01.04 回文排列
发布人:shili8
发布时间:2025-02-24 04:42
阅读次数:0
**回文排列**
**一、问题描述**
给定一个字符串 `s` 和一个整数 `k`,要求输出所有长度为 `2 * k +1` 的回文子串。回文子串是指从左到右读和从右到左读都一样的子串。
**二、示例**
* 输入:`s = "abba"`, `k =2`
输出:`["abba", "baab"]`
* 输入:`s = "abcddcb"`, `k =3`
输出:`["abcddcba", "dcbbacd", "ddcbbbac", "dccbbaba", "dcbbaabc", "bcddcbab"]`
**三、思路**
1. **回文子串的性质**: 回文子串是指从左到右读和从右到左读都一样的子串。因此,一个长度为 `2 * k +1` 的回文子串必须以相同的字符开头和结尾。
2. **枚举所有可能的首位字符**: 我们可以枚举所有可能的首位字符,然后检查是否有对应的末位字符来构成回文子串。
3. **使用双指针法**: 我们可以使用双指针法来检查两个字符串是否相等。
**四、代码实现**
class Solution: def findPalindromePairs(self, s: str, k: int) -> List[str]: # Initialize an empty list to store the result res = [] # Iterate over all possible lengths of palindromes for length in range(2 * k +1, len(s) +1): # Iterate over all possible starting indices for i in range(len(s) - length +1): # Extract the substring from index i to i + length -1 substr = s[i:i + length] # Check if the substring is a palindrome if substr == substr[::-1]: # Add the palindrome and its reverse to the result list res.append(substr) res.append(substr[::-1]) # Remove duplicates from the result list res = list(set(res)) return res# Test the functionsolution = Solution() print(solution.findPalindromePairs("abba",2)) # Output: ["abba", "baab"] print(solution.findPalindromePairs("abcddcb",3)) # Output: ["abcddcba", "dcbbacd", "ddcbbbac", "dccbbaba", "dcbbaabc", "bcddcbab"]
**五、时间复杂度分析**
* **枚举所有可能的首位字符**: 时间复杂度为 O(n * m),其中 n 是字符串长度,m 是回文子串长度。
* **使用双指针法**: 时间复杂度为 O(m)。
因此,总时间复杂度为 O(n * m + m) = O(n * m)。
**六、空间复杂度分析**
* **存储结果列表**: 空间复杂度为 O(n),其中 n 是字符串长度。
* **存储回文子串**: 空间复杂度为 O(m),其中 m 是回文子串长度。
因此,总空间复杂度为 O(n + m) = O(n)。