添加131.分割回文串python3版本

This commit is contained in:
ironartisan
2021-08-24 14:43:28 +08:00
parent cf6edd67cd
commit 0ab400b0fc

View File

@ -292,7 +292,8 @@ class Solution {
```
Python
```py
```python
# 版本一
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
@ -310,7 +311,36 @@ class Solution:
return res
```
```python
# 版本二
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
path = [] #放已经回文的子串
# 双指针法判断是否是回文串
def isPalindrome(s):
n = len(s)
i, j = 0, n - 1
while i < j:
if s[i] != s[j]:return False
i += 1
j -= 1
return True
def backtrack(s, startIndex):
if startIndex >= len(s): # 如果起始位置已经大于s的大小说明已经找到了一组分割方案了
res.append(path[:])
return
for i in range(startIndex, len(s)):
p = s[startIndex:i+1] # 获取[startIndex,i+1]在s中的子串
if isPalindrome(p): # 是回文子串
path.append(p)
else: continue #不是回文,跳过
backtrack(s, i + 1)
path.pop() #回溯过程弹出本次已经填在path的子串
backtrack(s, 0)
return res
```
Go
> 注意切片go切片是披着值类型外衣的引用类型