-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path132.palindrome partitioning
41 lines (40 loc) · 997 Bytes
/
132.palindrome partitioning
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public int minCut(String s) {
int dp[]=new int[s.length()];
Arrays.fill(dp,-1);
int mi=helper(0,s,0,dp)-1;
for(int i=0;i<dp.length;i++){
System.out.print(dp[i]+" ");
}
return mi;
}
static int helper(int index,String s,int c,int dp[]){
if(index>=s.length()){
return 0;
}
int min=Integer.MAX_VALUE;
if(dp[index]!=-1){
return dp[index];}
for(int i=index;i<s.length();i++){
String p=s.substring(index,i+1);
if(palindrome(p)){
int cost=1+helper(i+1,s,c,dp);
min=Math.min(min,cost);
}
}
dp[index]=min;
return min;
}
static boolean palindrome(String s){
int i=0;
int j=s.length()-1;
while(i<j){
if(s.charAt(i)!=s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
}