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.

一刷
题解:
初始定义一个一维数组minCuts,用来表示s.substring(0, i + 1)时的最小cut数。

再定义一个二维布尔数组isPalindrome,用来表示 s.substring(j, i)是否是palindrome。

核心算法是,假如isPalindrome[j][i]是palindrome,说明 j - 1至i + 1只需要1个cut, 因此对每一个i, minCuts[i]可以进行更新 - 比较现有 minCuts[i] 与 minCuts[j - 1] + 1。 这里也是一个一维的dp。

public class Solution {
    public int minCut(String s) {
        int len = s.length();
        int[] minCuts = new int[len]; //minCuts[i] is min cut for s.substring(0, i+1)
        boolean[][] isPalindrome = new boolean[len][len];
        
        for(int i=0; i

二刷
思路同上

public class Solution {
    public int minCut(String s) {
        int len = s.length();
        int[] minCuts = new int[len];
        Arrays.fill(minCuts, Integer.MAX_VALUE);
        boolean[][] isPalin = new boolean[len][len];
        
        for(int i=0; i

你可能感兴趣的:(132. Palindrome Partitioning II)