mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
添加131.分割回文串python3版本
This commit is contained in:
@ -292,7 +292,8 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
```py
|
```python
|
||||||
|
# 版本一
|
||||||
class Solution:
|
class Solution:
|
||||||
def partition(self, s: str) -> List[List[str]]:
|
def partition(self, s: str) -> List[List[str]]:
|
||||||
res = []
|
res = []
|
||||||
@ -310,7 +311,36 @@ class Solution:
|
|||||||
return res
|
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:
|
||||||
> 注意切片(go切片是披着值类型外衣的引用类型)
|
> 注意切片(go切片是披着值类型外衣的引用类型)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user