Leetcode 132. Palindrome Partitioning II

来源:互联网 发布:旅行水杯 知乎 编辑:程序博客网 时间:2024/05/21 21:42

Question

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.

code

/**
* DP方式解决
*
* @param s
* @return
*/
public int minCut(String s) {

    if (s == null || s.length() == 0) {        return 0;    }    boolean[][] flag = new boolean[s.length()][s.length()];    int[] len = new int[s.length() + 1];    len[0] = -1;    for (int i = 1; i <= s.length(); i++) {        len[i] = Integer.MAX_VALUE;        for (int j = 0; j < i; j++) {            flag[j][i - 1] = s.charAt(j) == s.charAt(i - 1) && (i - j <= 2 || flag[j + 1][i - 2]);            if (flag[j][i - 1]) {                len[i] = Math.min(len[i], len[j] + 1);            }        }    }    return len[s.length()];}
0 0
原创粉丝点击