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 =
Return
首先找出所有可能的回文情况,使用DP的方法的话时间复杂度为O(n^2),情况如下:"aab"
,Return
1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.- i == j, dp[i][j] = true, 单个字符自己肯定是回文字符串
- i+1 == j, dp[i][j] = true, 两个字符的时候相等的话就是回文字符串
- 其他情况,当i和j的字符相同而且dp[i+1][j-1]为回文的话,那么dp[i][j]也是回文
public int minCut(String s) { if(s == null) return 0; int n = s.length(); boolean[][] dp = new boolean[n][n]; for(int i = n-1; i >= 0; i--) { for(int j = i; j < n; j++) { if(i == j) dp[i][j] = true; else if(i+1 == j) { if(s.charAt(i) == s.charAt(j)) dp[i][j] = true; else dp[i][j] = false; } else { if(dp[i+1][j-1] == true && s.charAt(i) == s.charAt(j)) dp[i][j] = true; else dp[i][j] = false; } } } int[] cut = new int[n]; for(int i = 0; i < n; i++) { cut[i] = Integer.MAX_VALUE; for(int j = 0; j <= i; j++) { if(j == 0 && dp[j][i] == true) cut[i] = 0; else if(dp[j][i] == true) cut[i] = Math.min(cut[j-1]+1, cut[i]); } } return cut[n-1]; }
没有评论:
发表评论