标签:
题目地址:https://leetcode.com/problems/palindrome-partitioning-ii/
题目解析:此问题可以使用动态规划,用一个数组保存前i个字符需要的最少cut数,前i+1个字符串的最小cut数为前j个字符所需的cut数(j+1到i个字符为回文)+1;
题目解答:
public class Solution { public int minCut(String s) { if(s == null || s.length() == 0){ return 0; } int[] cutNum = new int[s.length()+1]; boolean[][] palindromeMap = new boolean[s.length()][s.length()]; cutNum[0] = -1; for(int i=1;i<=s.length();i++){ cutNum[i] = i-1; for(int j=0;j<=i-1;j++){ palindromeMap[j][i-1] = false; if(s.charAt(j) == s.charAt(i-1) && (i-1-j<=2 || palindromeMap[j+1][i-2])){ palindromeMap[j][i-1] = true; cutNum[i] = Math.min(cutNum[i], cutNum[j]+1); } } } return cutNum[s.length()]; } }
Leetcode Palindrome Partitioning II
标签:
原文地址:http://www.cnblogs.com/xiongyuesen/p/4443124.html