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];
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章