Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
A palindrome string is a string that reads the same backward as forward.
Example:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
s
?
1 <= s.length <= 16
.s
contain only lowercase English letters?
s
is empty, the function should return a list containing an empty list, i.e., [[]]
.class Solution:
def partition(self, s: str):
res = []
def is_palindrome(sub):
return sub == sub[::-1]
def backtrack(start, path):
if start == len(s):
res.append(path[:])
return
for end in range(start + 1, len(s) + 1):
substring = s[start:end]
if is_palindrome(substring):
path.append(substring)
backtrack(end, path)
path.pop()
backtrack(0, [])
return res
def is_palindrome(sub):
return sub == sub[::-1]
backtrack
):
start
: index in the string s
from where we start trying to partition.path
: stores the current list of palindromic substrings.start
equals the length of s
, it means we’ve partitioned the entire string, so we add the current path
to res
.start
position.
start
to end
is a palindrome, add it to the current path and recurse with the new start position (end
).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?