【Leetcode】Palindrome Partitioning II
2016-06-11 10:13
260 查看
题目链接:https://leetcode.com/problems/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
c[i]表示从下标0~i的字符串 最少由几个回文串组合而成
dp[i][j]表示下标j~i的字符串是否是回文串
状态转移方程:
0<=j<=i
if j~i是回文串
c[i]=min{c[j-1]+1,c[i]}
这里判断j~i是否是回文串不能暴力判断了否则会超时,需要利用之前判断过的结果。即若charAt[j]==charAt[i] &&dp[j+1][i-1],则dp[j][i]也是回文串。
这里要注意边界情况,即当j=i或j+1==i时,若charAt[j]==charAt[i],则j~i也是回文串,防止出现对j+1>i-1的判断。
时间复杂度O(n^2),空间复杂度O(n^2)。
算法:
题目:
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
c[i]表示从下标0~i的字符串 最少由几个回文串组合而成
dp[i][j]表示下标j~i的字符串是否是回文串
状态转移方程:
0<=j<=i
if j~i是回文串
c[i]=min{c[j-1]+1,c[i]}
这里判断j~i是否是回文串不能暴力判断了否则会超时,需要利用之前判断过的结果。即若charAt[j]==charAt[i] &&dp[j+1][i-1],则dp[j][i]也是回文串。
这里要注意边界情况,即当j=i或j+1==i时,若charAt[j]==charAt[i],则j~i也是回文串,防止出现对j+1>i-1的判断。
时间复杂度O(n^2),空间复杂度O(n^2)。
算法:
public int minCut(String s) { if (s.length() == 0) return 0; int c[] = new int[s.length()];// 0~i的字符串最少是几个回文串的组合 boolean dp[][] = new boolean[s.length()][s.length()];// 从i~j字符串是否是回文 for (int i = 0; i < s.length(); i++) { dp[i][i] = true; c[i] = i + 1; for (int j = 0; j <= i; j++) { if (s.charAt(j) == s.charAt(i) && (j == i || j + 1 == i || dp[j + 1][i - 1])) { dp[j][i] = true; if (j > 0) { c[i] = Math.min(c[i], c[j - 1] + 1); } else { c[i] = Math.min(c[i], 1); } } } } return c[s.length() - 1] - 1; }
相关文章推荐
- 新家
- LBP(局部二进制模式)
- #import"C:\Program Files
- 运算符重载
- java学习笔记之线程操作方法总结
- Kettle_设置变量的两种方法
- ReactJs笔记
- xcode中使用xib添加autolayout中constrain to margins的不同
- 最大子序列
- 用ftplib爆破FTP口令
- 自定义View相关的博客收藏
- JavaSE 复习_4 接口多态和内部类
- Android网络图片处理——Picasso与HttpUrlConnection比较
- C++ c++与C语言的区别(实用性增强,register关键字增强,全局变量检测增强)
- 灰度共生矩阵
- Flask学习-设备管理系统4:修改设备信息
- LinearLayoutCompat分割线效果源码分析
- 【Java并发编程】并发编程大合集
- 二叉搜索树(二叉排序搜索树)
- 【java】 java 实现mysql备份