LeetCode 132 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.

思路:1.推断字符串的字串S.subString(i,j) [i<=j]是否为为回文子串,用boolean型的二维数组isPalindrome来存储该结果

在这个地方用了点小技巧,isPalindrome[i]j]会依赖于sPalindrome[i+1]j-1]  [i+2<=j].
           2.使用动态规划的思想,若S.subString(i,j) 是回文字符串,则仅仅要看 ans[i] - 1 > ans[j - 1]是否成立,若成立,则更新他

public class Solution {
	public int minCut(String s) {
		int[] ans = new int[s.length()];
        boolean[][] isPalindrome = new boolean[s.length()][s.length()];
        for (int i = 0; i < s.length(); i++) 
            isPalindrome[i][i] = true;
        
        for (int i = 0; i < s.length() - 1; i++) 
            isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1));
        

        for (int length = 2; length < s.length(); length++) {
            for (int start = 0; start + length < s.length(); start++) {
                isPalindrome[start][start + length]
                    = isPalindrome[start + 1][start + length - 1] && s.charAt(start) == s.charAt(start + length);
            }
        }
        
		for (int i = 1; i < s.length(); i++) {
			if (isPalindrome[0][i])
				continue;
			ans[i] = Integer.MAX_VALUE;
			for (int j = 1; j <= i; j++) {
				if (isPalindrome[j][i] && ans[i] - 1 > ans[j - 1]) {
					ans[i] = 1 + ans[j - 1];
				}
			}
		}
		return ans[s.length() - 1];
	}
}


posted @ 2017-06-26 14:28  yfceshi  阅读(103)  评论(0编辑  收藏  举报