Given a string s, cut s into some substrings such that every substring is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example
Given s = "aab"
,
Return 1
since the palindrome partitioning ["aa", "b"] could be produced using1 cut.
public class Solution { /** * @param s a string * @return an integer */ public int minCut(String s) { // write your code here if(s == null || s.length() == 0) return 0; int len = s.length(); boolean[][] isPalindrome = new boolean[len][len]; for(int i = 0; i < len; i++){ isPalindrome[i][i] = true; } for(int i = 0; i < len - 1; i++) isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1)); for(int i = len - 1; i >= 0; i--){ for(int j = i + 2; j < len; j++){ if(s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1]) isPalindrome[i][j] = true; else isPalindrome[i][j] = false; } } if(isPalindrome[0][len - 1]) return 0; int[] f = new int[s.length()]; for (int i = 0; i < s.length(); i++) { f[i] = i; } for (int i = 0; i < s.length(); i++) { if(isPalindrome[0][i]) f[i] = 0; else for (int j = 0; j < i; j++) if(isPalindrome[j + 1][i]) f[i] = Math.min(f[i], f[j] + 1); } return f[len - 1]; } public boolean valid(String s){ int left = 0; int right = s.length() - 1; while(left < right){ if(s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } };
时间: 2024-10-05 05:02:40