2023.6.27
用all函数判断回文串
用两个指针从字符串两端向中间遍历,最后用all函数判断是否全为True
一个简单的改进就是在遍历时只要发现不一样直接返还False,避免每次都对字符串进行完整的遍历
class Solution:
def partition(self, s: str) -> List[List[str]]:
self.s = s
self.n = len(s)
self.result = []
self.path = []
self.backtracking(0)
return self.result
def backtracking(self, startindex):
if startindex == self.n: # 超出字符串s的长度
self.result.append(self.path[:])
return
for i in range(startindex, self.n):
sub = self.s[startindex:i+1]
if not self.isPalindrome(sub): # 如果不是回文串
continue
# 如果是回文串
self.path.append(sub)
self.backtracking(i+1)
self.path.pop()
def isPalindrome(self, s):
return all(s[i] == s[len(s) - 1 - i] for i in range(len(s) // 2))
def isPalindrome(self, s):
for i in range(len(s) // 2):
if s[i] != s[len(s) - 1 - i]:
return False
return True
极速版回文串判断(哈希)
用一个n*n的矩阵,i,j记录s[i:j+1]是不是回文串
那么只用查询isPalindrome[i][j]就直到s[i:j+1]是不是回文串
class Solution:
def partition(self, s: str) -> List[List[str]]:
self.s = s
self.n = len(s)
self.result = []
self.path = []
self.isPalindrome = [[False] * self.n for _ in range(self.n)]
self.isP()
# n*n的矩阵,i,j记录s[i:j+1]是不是回文串
self.backtracking(0)
return self.result
def backtracking(self, startindex):
if startindex == self.n: # 超出字符串s的长度
self.result.append(self.path[:])
return
for i in range(startindex, self.n):
sub = self.s[startindex:i+1]
if not self.isPalindrome[startindex][i]: # 如果不是回文串
continue
# 如果是回文串
self.path.append(sub)
self.backtracking(i+1)
self.path.pop()
def isP(self):
for i in range(self.n-1, -1, -1):
for j in range(i, self.n):
if i == j: # 单元素子串
self.isPalindrome[i][j] = True
elif j - i == 1: # 连续两个元素子串
self.isPalindrome[i][j] = (self.s[i] == self.s[j])
else: # 其他子串
self.isPalindrome[i][j] = (self.s[i] == self.s[j] and self.isPalindrome[i+1][j-1])