Palindrome Partitioning in Python

0 min read 70 words

The problem

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

The solution

def partition(self, s: str) -> List[List[str]]:
    ret = []
    def isPal(s):
        return s == s[::-1]

    def fn(s, l):
        if not s:
            ret.append(l)
            return
        for i in range(1, len(s)+1):
            if isPal(s[:i]):
                fn(s[i:], l+[s[:i]])
    fn(s, [])
    return ret
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags