Palindrome Partitioning II

来源:互联网 发布:王充 论衡 知乎 编辑:程序博客网 时间:2024/06/07 15:40

Q:

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:

public class Solution {    public int minCut(String s) {        if (s == null || s.length() <= 1)            return 0;        int[] cut = new int[s.length()+1];        cut[s.length()] = 0;        boolean[][] pal = new boolean[s.length()][s.length()];        for (int i = s.length()-1; i >= 0; i--) {            cut[i] = s.length() - i;            for (int j = i; j < s.length(); j++) {                if (s.charAt(i) == s.charAt(j) && ( j - i <= 1 || pal[i+1][j-1])) {                    pal[i][j] = true;                    cut[i] = Math.min(cut[i], 1+cut[j+1]);                }            }        }        return cut[0] - 1;    }}


0 0