132. Palindrome Partitioning II
来源:互联网 发布:linux mysql 存放路径 编辑:程序博客网 时间:2024/05/01 17:59
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解法好了。
1、建立cut[n]来保存每一个字符处能切次数的最小值,如果s[j, i]是回文,那么cut[i] = cut[j - 1]+1
2、建立isPalindrome[n][n]数组保存s[j, i]是不是回文,如果s[j, i]是回文,那么肯定s[j] == s[i],而且isPalindrome[j+1][i-1]==true,这时候就需要更新cut[i] = cut[j-1]
代码如下:
public class Solution { public int minCut(String s) { int len = s.length(); int[] cut = new int[len]; boolean[][] isPalindrome = new boolean[len][len]; char[] cs = s.toCharArray(); for (int i = 0; i < len; i ++) { int min = i; for (int j = 0; j <= i; j ++) { if (cs[i] == cs[j] && (j + 1 > i -1 || isPalindrome[j + 1][i - 1])) { isPalindrome[j][i] = true; min = Math.min(min, j == 0? 0: cut[j - 1] + 1); } } cut[i] = min; } return cut[len - 1]; }}另一种O(n)space的方法,不需要isPalindrome[n][n]数组,是遍历s[n],每次的s[i]向外发散,分为奇数序列和偶数序列两种情况,然后动态更新cut[i]也很巧妙,代码如下:
public class Solution { public int minCut(String s) { int n = s.length(); char cs[] = s.toCharArray(); int[] cut = new int[n + 1]; // number of cuts for the first k characters for (int i = 0; i <= n; i++) cut[i] = i-1; for (int i = 0; i < n; i++) { for (int j = 0; i-j >= 0 && i+j < n && cs[i-j]==cs[i+j] ; j++) // odd length palindrome cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j]); for (int j = 1; i-j+1 >= 0 && i+j < n && cs[i-j+1] == cs[i+j]; j++) // even length palindrome cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j+1]); } return cut[n]; }}
0 0
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- 131. Palindrome Partitioning && 132. Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II
- [LeetCode]132.Palindrome Partitioning II
- vc 删除文件保留目录
- 数据结构 - 线性表之顺序表 (c 语言)
- C#常用命令库(备用)
- 【video】PPTV聚力年后或将改名苏宁视频 聚力体育划归苏宁搬至南京
- CentOS故障排除详解(3): 网络环境
- 132. Palindrome Partitioning II
- Cocos2d-x 3.x 图形学渲染系列二十四
- php与mysql的增删改查
- 三星联合第三方机构认真排查获得Note7燃损原因并公之于众
- (转)智能投顾的大赢家,仍然会是传统机构
- CCF201509-1 数列分段(100分)
- 安装记录 win8 vs2012 sqlserver2012 iis8
- 如何转载CSDN里的好博文?
- Leetcode 22. Generate Parentheses