LeetCode每日一题:回文字符串 2

问题描述

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",
Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.

问题分析

这道题其实用上道的方法也是能做的,但是会超时,所以用到动态规划来解决这道题目。
首先定义状态转移方程:

  • cut[i],表示从第i个字符到最后一个字符所需要的最小切割数,那么我们所求的就是cut[0]了。cut[i]的初始值是s.length-1,表示所有的单个字符都得切开一遍
  • c[i][j],表示从第i个字符到第j个字符是否是回文,那么判断c[i][j]是否是回文就可以写成,c[i+1][j-1]是否是回文&&s[i]==s[j],满足状态转移方程了
  • c[i][j]一种特殊情况,当i==j时,表示只有一个字符,肯定是回文
    综合上述的分析,cut[i]的状态转移方程可以写为:
    cut[i]=min{cut[i],cut[j+1]+1}//i到j之间是否是回文
    cut[0]-1即为所求

代码实现

public int minCut(String s) {
        int len = s.length();
        int[] cut = new int[len + 1];
        boolean[][] c = new boolean[len + 1][len + 1];
        if (s.length() == 0) return 0;
        for (int i = 0; i < len; i++) {
            cut[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)) {
                    c[i][j] = true;
                    cut[i] = Math.min(cut[i], cut[j + 1] + 1);
                } else if (s.charAt(i) == s.charAt(j) && c[i + 1][j - 1]) {
                    c[i][j] = true;
                    cut[i] = Math.min(cut[i], cut[j + 1] + 1);
                }
            }
        }
        return cut[0] - 1;
    }

你可能感兴趣的:(LeetCode每日一题:回文字符串 2)