Palindrome Partitioning II Leetcode
来源:互联网 发布:prototype.js 1.6下载 编辑:程序博客网 时间:2024/05/30 23:37
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.
给定一个字符串s,将s分割成一些子串,使每个子串都是回文。
比如,给出字符串s = "aab",
返回 1, 因为进行一次分割可以将字符串s分割成["aa","b"]这样两个回文子串
使用动态规划解决这道问题,我们需要初始化两个数组,
一个int数组cuts[i]纪录前i个字符最小的切割次数,
一个boolean数组dp[i][j]用于纪录从第i个位置到第j个位置是否是回文。
怎样用动态规划的思想判断从i到j之间的字符是否是回文呢,大致分为三种情况。
(1)如果i == j,也就是i和j是同一个位置的字符,一个字符肯定是回文。
(2)如果i和j是相邻的两个位置并且字符相等,i= j + 1,s.charAt(i) == s.charAt(j), 则是回文。
(3)如果i和j不想等也不相邻,如果dp[j + 1][i - 1]是回文,并且s.charAt(i) == s.charAt(j), 则是回文。
cuts[i]= i 设置最大的切割次数,前i个字符如果切割,最多切i次。
如果i到j之间是回文串,如果j大于0,说明从起始点到i之间右被切割出来一块i~j的回文,
有可能i和j是相邻的,也有可能是相隔了几个字符的,
前i个字符被切割的最小次数为 cuts[i] 和 cuts[j -1] +1的较小值,
这里的1指得是前i个字符中,从j到i这一块最少切割出来一次。
如果j =0,说明前i个字符串本身就是回文串,不需要在次切割,最小的切割次数为0
public class Solution { public int minCut(String s) { int n = s.length(); int[] cuts = new int[n]; boolean[][] dp = new boolean[n][n]; for (int i = 0; i < n; i++) { cuts[i] = i; for (int j = 0; j <= i; j++) { if (s.charAt(i) == s.charAt(j) && (i - j <= 1 || dp[j + 1][i - 1])) { dp[j][i] = true; if (j > 0) { cuts[i] = Math.min(cuts[i], cuts[j - 1] + 1); } else { cuts[i] = 0; } } } } return cuts[n -1]; }}
0 0
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- LeetCode - Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- LeetCode Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- 判断当前rom为MIUI或Flyme或android m
- Android Studio 主题、字体大小的设置
- 《Windows核心编程》之“线程调度和优先级”
- 后缀数组
- bios x86保护模式下的软盘操作floppy
- Palindrome Partitioning II Leetcode
- 【usaco 2013 feb Bronze】信息传递
- == 判别中的坑
- c++学习笔记之虚函数
- ios应用一调起应用二并传递参数
- Linux-SSH命令学习
- log4j.xml 日志持久化本地配置
- CSU1513 Kick the ball!
- 倒计时