[Java] 132. Segmentation of palindrome II---learn dynamic programming! ! !

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:

Input: s = "aab"
Output: 1
Explanation: You can split s into two palindrome substrings like ["aa", "b"] only once.
Example 2:

Input: s = "a"
Output: 0
Example 3:

Input: s = "ab"
Output: 1

prompt:

1 <= s.length <= 2000
s only consists of lowercase English letters

代码:
public int minCut(String s) {
    
    
		int n = s.length();
		boolean[][] judge = new boolean[n][n];
		int[] dp = new int[n]; // dp[i]表示s中第i个字符到第(n-1)个字符所构成的子串的最小分割次数
		for (int i = n - 1; i >= 0; i--) {
    
    
			dp[i] = Integer.MAX_VALUE;
			for (int j = i; j < n; j++) {
    
    
				if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || judge[i + 1][j - 1])) {
    
    
					judge[i][j] = true;
					if (j + 1 < n) {
    
    
						dp[i] = Math.min(dp[i], 1 + dp[j + 1]);
					}else{
    
    
						dp[i] = 0;
					}
				}
			}
		}
		return dp[0];
	}

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114529188