http://leetcode.com/onlinejudge#question_132
Question:
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.
Solution:
DP problem, but my first try failed due to time limitation. The root cause is you should try to optimize the Palindrome calculation. The solution below borrows from others idea found from the discussion page. Thanks to the author.
public class Solution {
public int minCut(String s) {
int leng = s.length();
if(leng == 0 || leng == 1) return 0;
boolean[][] isPal = new boolean[leng][leng];
int[] dp = new int[leng];
for (int i = 0; i < leng; i++) {
dp[i] = leng - 1 - i;
}
for (int i = leng - 1; i >= 0; --i) {
for (int j = i; j < leng; ++j) {
if (s.charAt(i) == s.charAt(j) && (j <= i + 2 || (i + 1 < leng && j - 1 >= 0 && isPal[i + 1][j - 1]))) {
isPal[i][j] = true;
if(j+1 < leng){
dp[i] = Math.min(dp[i], 1 + dp[j + 1]);
}else {
dp[i] = 0;
}
}
}
}
return dp[0];
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s = new Solution();
int cut = s.minCut("abccdcba");
System.out.println(cut);
}
}
分享到:
相关推荐
LeetCode Palindrome Number解决方案
Determine whether an integer is a palindrome. Do this without extra space. Java AC版本
leetcode 分类 LeetCode Progress 128/154 Other Solutions C++,有详细思路解释 python,部分有解释 ...Partitioning II Maximal Rectangle ###Recursion N-Queens N-Queens II Balanced Binary Tree Binar
刷LeetCode刷LeetCode刷LeetCode刷LeetCode刷LeetCode
leetcode卡leetcode_practices_learncard_recursionii 我的 leetcode 递归练习 ii 学习卡在 100% 完成 :) 我的 Java8 备忘单:
462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/...
Palindrome LeetCode 167 Two Sum II - Input array is sorted LeetCode 344 Reverse String LeetCode 345 Reverse Vowels of a String 2 字符串 编号 题目 LeetCode 3 Longest Substring Without Repeating ...
大佬的leetcode刷题笔记(c++版本)
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101.zip
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101_源码.zip
Leetcode\PalindromeNumber\PalindromeNumber.cs 问题: 从排序数组中删除重复项 代码: Leetcode\RemoveDuplicates\RemoveDuplicates.cs 问题: 买卖股票的最佳时机 II 代码: Leetcode\MaxProfit\MaxProfit.cs ...
vs code LeetCode 插件
vscode安装leetcode 回文 这是分支、循环和其他基本 C# 概念的练习,以构建工作控制台应用程序。5/5/2020 由 Nitun Dtta 和 Matt Stroud 制作 描述 这是一个控制台应用程序,允许用户提供任何单词、短语、数字或其他...
leetcode中文版
terminal-leetcode, 终端Leetcode是基于终端的Leetcode网站查看器 终端 leetcode终端leetcode是基于终端的leetcode网站查看器。本项目是由 RTV 激发的。 我最近正在学习本地化的反应,以实践我的新知识,并根据这个...
100个leetCode详细解答
LeetCode 刷题汇总1
LeetCode 选讲1
leetcode刷题, 直接用leetcode的分类方式.