Leetcode problem solution 132-split palindrome II

Problem Description

Give you a string s, please split s into some substrings so that each substring is a palindrome.

Returns the minimum number of splits that meet the requirements.

Example 1:

输入:s = "aab"
输出:1
解释:只需一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。

Example 2:

输入:s = "a"
输出:0

Example 3:

输入:s = "ab"
输出:1
 

prompt:

1 <= s.length <= 2000
s 仅由小写英文字母组成

Problem-solving ideas

Let f[i] denote the minimum number of divisions of the prefix s[0...i] of the string. To get the value of f[i], we can consider enumerating the last palindrome divided by s[0...i], so that we can write the state transition equation:
Insert picture description here
that is, we enumerate the last palindrome The starting position of j+1, to ensure that s[j+1...i] is a palindrome string, then f[i] can be transferred from f[j] with an additional number of divisions.

Note that in the above state transition equation, we have yet to consider a case, that is, s[0...i] itself is a palindrome string. At this time, it does not need to be divided, namely:

f[i]=0

So how do we know whether s[j+1...i] or s[0...i] is a palindrome? We can use the same pre-processing method as in Leetcode Problem Solution 5-Longest Palindrome Substring to calculate whether each substring of the string ss is a palindrome in advance, namely:

Code

class Solution {
    
    
    public boolean f[][];     //判断以i为起点,j为终点的字符串是否是回文串
    public int n;             //字符串s的长度
    public int dp[];          //dp[i]表示以i为最后一个元素的子字符串的最少分割次数
    public int minCut(String s) {
    
    
        n=s.length();
        //按最长回文子串的思路填充f[][]
        f=new boolean[n][n];
        if(n==0 || n==1){
    
    
            return 0;
        }
        char []cs=s.toCharArray();
        for(int i=0;i<n;i++){
    
    
            for(int j=0;j<=i;j++){
    
    
                if(i-j<=1){
    
    
                    if(cs[i]==cs[j]){
    
    
                        f[j][i]=true;
                    }
                }else{
    
    
                    if(cs[i]==cs[j] && f[j+1][i-1]==true){
    
    
                        f[j][i]=true;
                    }
                }
            }
        }
        dp=new int[n];
        //计算以每个元素为后缀的子字符串的最少分割次数
        for(int i=0;i<n;i++){
    
    
            dp[i]=i;    //最坏情况下,默认每个字符都要分割
            //如果从第一个元素一直到最后一个元素都是回文子串,那么最少分割次数是0
            if(f[0][i]==true){
    
      
                dp[i]=0;
                continue;
            }
            //否则的话,从前往后遍历,如果从j+1到i可以组成一个回文子串
            //那么最少分割次数就等于0到j的最少分割次数+1
            for(int j=0;j<i;j++){
    
    
                if(f[j+1][i]==true){
    
    
                    dp[i]=Math.min(dp[j]+1,dp[i]);
                }
            }
        }
        //最终返回dp[n-1]
        return dp[n-1];
    }
    
}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/114542203