leetcode Palindrome Partitioning II

来源:互联网 发布:新浪模拟炒股软件 编辑:程序博客网 时间:2024/06/04 01:35

leetcode Palindrome Partitioning II 原题地址:

https://oj.leetcode.com/problems/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.

给定一个字符串,求最小划分,使得所有划分后的子串为回文字符串。

从后往前数,用cuts[i]来表示i...n的最小划分,在i...n中如果存在j使得i...j为回文,那么可以更新cuts[i] = min(cuts[i], cuts[j+1] + 1) /*i...j为回文,cuts[j+1]为j+1...n的最小划分*/ 而i...j是否为回文可以用动态规划来得到。

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


0 0