Palindrome Partitioning II
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
思路:
动态规划
我的代码1:(思路和代码都是正确的,但是对于大数据超时啊) http://www.lintcode.com/zh-cn/problem/palindrome-partitioning-ii/ 都通过不了啊
public class Solution { public int minCut(String s) { if(s==null || s.length()==0 || isPalindrome(s)) return 0; int len = s.length(); int[] record = new int[len]; for(int i=0; i<len; i++) { int min = Integer.MAX_VALUE; for(int j=0; j<=i; j++) { String sub = s.substring(j,i+1); if(isPalindrome(sub)) { min = Math.min(min, (j==0?0:1+record[j-1])); } } record[i] = min; } return record[len-1]; } public boolean isPalindrome(String part) { int len = part.length(); for(int i = 0; i < len/2; i++) { char first = part.charAt(i); char last = part.charAt(len - 1 - i); if(first != last) return false; } return true; } }
我的代码2:用另外一个数组记录已经成功的substring http://www.lintcode.com/zh-cn/problem/palindrome-partitioning-ii/ 可以通过了
public class Solution { public int minCut(String s) { if(s==null || s.length()==0 || isPalindrome(s)) return 0; int len = s.length(); int[] record = new int[len]; boolean[][] isValid = new boolean[len][len]; for(int i=0; i<len; i++) { int min = Integer.MAX_VALUE; for(int j=0; j<=i; j++) { String sub = s.substring(j,i+1); if(isValid[j][i]) { min = Math.min(min, (j==0?0:1+record[j-1])); continue; } if(isPalindrome(sub)) { min = Math.min(min, (j==0?0:1+record[j-1])); isValid[j][i] = true; } } record[i] = min; } return record[len-1]; } public boolean isPalindrome(String part) { int len = part.length(); for(int i = 0; i < len/2; i++) { char first = part.charAt(i); char last = part.charAt(len - 1 - i); if(first != last) return false; } return true; } }
posted on 2016-10-29 15:38 zhouzhou0615 阅读(179) 评论(0) 编辑 收藏 举报