131. Palindrome Partitioning

Tapan RachchhTapan Rachchh
1 min read
class Solution:
    def partition(self, s: str) -> List[List[str]]:
        def checkPalindrome(word):
            return word == word[::-1]

        ans = []
        def backtrack(index, prev, temp):
            nonlocal ans
            if index >= len(s):
                if checkPalindrome(prev):    
                    ans.append(temp + [prev])                        
                return

            if checkPalindrome(prev):
                backtrack(index + 1, s[index], temp + [prev]) 

            backtrack(index + 1, prev + s[index], temp)

        backtrack(1, s[0], [])
        return ans
0
Subscribe to my newsletter

Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tapan Rachchh
Tapan Rachchh