[和小菜雞一起刷題(python)] LeetCode 131. 分割回文串 (Palindrome Partitioning)
阿新 • • 發佈:2019-01-04
LeetCode 131. 分割回文串 (Palindrome Partitioning)
原題
給定一個字串 s,將 s 分割成一些子串,使每個子串都是迴文串。
返回 s 所有可能的分割方案。
示例:
輸入: “aab”
輸出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
思路
題目要求返回所有的可能方案,所以依舊採用回溯演算法。迴圈檢視當前字串的每一個可切分位置位;判斷若在當前位置切分,前半部分是否是迴文串。若是,則將前半部分存入當前解,並遞迴分割後半部分。
例如輸入字串為示例:
|a |a |b |
0 1 2 3
首先判斷分割位1,發現前半部分‘a’是迴文串,將‘a’存入cur_res,將後半部分‘ab’用作遞迴。當輸入字串為空時,遞迴結束,將cur_res加入的result,最終返回result。
程式碼
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
if len(s) == 0:
return []
else:
res = []
self.partition_helper(s, [], res)
return res
def partition_helper (self, s, cur_res, result):
if len(s) == 0:
result.append(cur_res)
for i in range(1, len(s)+1):
if self.check(s[:i]):
self.partition_helper(s[i:], cur_res + [s[:i]], result)
def check(self, s):
if len(s) == 0:
return False
else:
start = 0
end = len(s) - 1
while start <= end:
if s[start] != s[end]:
return False
else:
start += 1
end -= 1
return True