131. Palindrome Partitioning Leetcode Solution
Palindrome Partitioning Leetcode 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: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Palindrome Partitioning Leetcode Solution :
Constraints :
- 1 <= s.length <= 16
- s contains only lowercase English letters.
Example 1:
- Input: s = “a”
- Output: [[“a”]]
Approach :
- At every index, check if curr string is palindrome
- If yes, then break string and add to partition and check for next index
- Similarly, check by not breaking the string at current index
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
C++
Java
Python
C++
class Solution { public: bool is_palin(string& str) { int start=0 , end=str.length()-1; while(start< end) { if(str[start++]!=str[end--])return false; } return true; } void solve(int ind,string& s,string curr,vector< string> part,vector< vector< string>>& ans) { if(ind==s.length()) { if(curr.length()>0 && is_palin(curr)) { part.push_back(curr); ans.push_back(part); } return; } solve(ind+1,s,curr+s[ind],part,ans); if(curr.length()>0 && is_palin(curr)) { part.push_back(curr); curr=s[ind]; solve(ind+1,s,curr,part,ans); part.pop_back(); } } vector< vector< string>> partition(string s) { vector< vector< string>>ans; vector< string>part; string curr=""; solve(0,s,curr,part,ans); return ans; } };
Java
class Solution { List< List> ans = new ArrayList<>(); List< String> curr = new ArrayList<>(); boolean isPalindrome(String s, int low, int high) { while (low < high) if (s.charAt(low++) != s.charAt(high--)) return false; return true; } void genrate(String s,int start) { if(start >=s.length()) ans.add(new ArrayList<>(curr)); for(int i=start;i< s.length();i++) { if(isPalindrome(s,start,i)) { curr.add(s.substring(start,i+1)); genrate(s,i+1); curr.remove(curr.size()-1); } } } public List< List< String>> partition(String s) { genrate(s,0); return ans; } }
Python
class Solution: def partition(self, s: str) -> List[List[str]]: res=[] part=[] def dfs(i): if(i>=len(s)): res.append(part.copy()) return for j in range(i,len(s)): #partitioning the string.... if(self.is_polin(s,i,j)): part.append(s[i:j+1]) dfs(j+1) part.pop() dfs(0) return res def is_palin(self,s,l,r): while(l< r): if(s[l]!=s[r]): return False l+=1 r-=1 return True
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment