Palindrome Partitioning II

来源:互联网 发布:下载教育平台软件 编辑:程序博客网 时间:2024/05/16 18:55

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.

public class Solution {    public int minCut(String s) {        int n = s.length();boolean [][] p = new boolean [n][n];int [] res = new int[n + 1];for (int i = 0; i < n + 1; i++) {res[i] = n-i-1;}for (int i = n - 1; i >= 0; i--) {for (int j = i  ; j < n; j++) {if (s.charAt(i) == s.charAt(j) && (j - i < 2 || p[i + 1][j - 1])) {p[i][j] = true;res[i] = min(res[i], res[j + 1] + 1);}}}return res[0];    }private int min(int a, int b){return a < b ? a : b;}}

也是DP,但只要用一维的结果就可以了。

0 0