-
Notifications
You must be signed in to change notification settings - Fork 1
/
Palindrome Partitioning II
35 lines (34 loc) · 1 KB
/
Palindrome Partitioning II
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
class Solution {
public int minCut(String s) {
HashMap<String,Integer> memo=new HashMap<String,Integer>();
return minimumCuts(s,0,s.length()-1,memo);
}
private int minimumCuts(String s, int start, int end,HashMap<String,Integer> memo){
if(isPalindrome(s,start,end)){
return 0;
}
String currentKey=start+"_"+end;
if(memo.containsKey(currentKey)){
return memo.get(currentKey);
}
int ans=1000000;
for(int i=start;i<end;i++){
if(isPalindrome(s,start,i)){
int tempAns=1+minimumCuts(s,i+1,end,memo);
ans=Math.min(ans,tempAns);
}
}
memo.put(currentKey,ans);
return ans;
}
private boolean isPalindrome(String s, int start, int end){
while(start<=end){
if(s.charAt(start)!=s.charAt(end)){
return false;
}
start++;
end--;
}
return true;
}
}