[Leetcode] Palindrome Partitioning II

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

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

 

Solution:

1  首先,利用createTable来标记所有是palindrome的片段。

 

2  初始化cut[]里的值

 

 

3  结合state表和cut表的初始值来update。

 

 1 public class Solution {
 2     public int minCut(String s) {
 3       if(s==null||s.length()==0||s.length()==1)
 4             return 0;
 5         int N=s.length();
 6         boolean[][] state=createTable(s);
 7         int[] cut=new int[N+1];
 8         cut[N-1]=0;
 9         for(int i=N-1;i>=0;--i){
10             cut[i]=N-i;
11             for(int j=i;j<N;++j){
12                 if(state[i][j]){
13                     cut[i]=Math.min(cut[i], 1+cut[j+1]);
14                 }
15             }
16         }
17         return cut[0]-1;
18     }
19 
20     private boolean[][] createTable(String s) {
21         // TODO Auto-generated method stub
22         boolean[][] b=new boolean[s.length()][s.length()];
23         for(int i=0;i<s.length();++i){
24             b[i][i]=true;
25         }
26         int low=0;
27         int high=0;
28         for(int i=1;i<s.length();++i){
29             //even
30             low=i-1;
31             high=i;
32             while(low>=0&&high<s.length()&&s.charAt(low)==s.charAt(high)){
33                 b[low--][high++]=true;
34             }
35             //odd
36             low=i-1;
37             high=i+1;
38             while(low>=0&&high<s.length()&&s.charAt(low)==s.charAt(high)){
39                 b[low--][high++]=true;
40             }
41         }
42         return b;
43     }
44 }

 ========================

2015-11-07

http://www.cnblogs.com/springfor/p/3891896.html

posted @ 2014-11-24 11:02  Phoebe815  阅读(246)  评论(0编辑  收藏  举报