Skip to content

Commit aacb295

Browse files
authoredFeb 3, 2024
132. Palindrome Partitioning II
1 parent 3221d0f commit aacb295

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
 

‎132. Palindrome Partitioning II

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
Q.No.->132. Palindrome Partitioning II
2+
Ans->
3+
class Solution {
4+
public:
5+
bool isPalindrome(string &s, int i, int j){
6+
while(i<j){
7+
if(s[i]!=s[j]) return false;
8+
i++; j--;
9+
}
10+
11+
return true;
12+
}
13+
14+
int solve(string &s, int i,vector<int> &dp){
15+
if(i==s.length()) return 0;
16+
17+
if(dp[i]!=-1) return dp[i];
18+
int minCost=INT_MAX;
19+
for(int j=i;j<s.length();j++){
20+
if(isPalindrome(s,i,j)){
21+
int cost=1+solve(s,j+1,dp);
22+
minCost=min(minCost,cost);
23+
}
24+
}
25+
26+
return dp[i]=minCost;
27+
28+
29+
}
30+
31+
int minCut(string s) {
32+
vector<int> dp(s.length()+1,-1);
33+
34+
//we subtract 1 because code includes a partition at the end of the string as well
35+
return solve(s,0,dp)-1;
36+
}
37+
};

0 commit comments

Comments
 (0)
Please sign in to comment.