本文主要是介绍**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.
这应该是动态规划,dp[i]维护字符串s的前i个字符为回文字符串的最小切分次数
http://www.programcreek.com/2014/04/leetcode-palindrome-partitioning-ii-java/
dp【】【】干什么的,没看懂o(╯□╰)o
public class Solution {public int minCut(String s) {int n = s.length();boolean dp[][] = new boolean[n][n];int cut[] = new int[n];for (int j = 0; j < n; j++) {cut[j] = j; //set maximum # of cutfor (int i = 0; i <= j; i++) {if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || dp[i+1][j-1])) {dp[i][j] = true;// if need to cut, add 1 to the previous cut[i-1]if (i > 0){cut[j] = Math.min(cut[j], cut[i-1] + 1);}else{// if [0...j] is palindrome, no need to cut cut[j] = 0; } }}}return cut[n-1];}
}
这篇关于**Palindrome Partitioning II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!