Palindrome Partitioning II
来源:互联网 发布:mac不识别u盘启动 编辑:程序博客网 时间:2024/04/26 08:27
Problem:
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开始。
Solution:
public class Solution {
public int minCut(String s) {
int slen = s.length();
boolean[][] palind = new boolean[slen][slen];
for(int i=slen-1;i>=0;i--)
{
for(int j=i;j<slen;j++)
{
palind[i][j] = (s.charAt(i)==s.charAt(j))&&((j-i<2)||palind[i+1][j-1]);
}
}
int[] minCut = new int[slen+1];
for(int i=0;i<slen+1;i++)
minCut[i] = i-1;
for(int i=0;i<slen;i++)
{
for(int j=i;j<slen;j++)
{
if(palind[i][j]&&minCut[i]<minCut[j+1])
{
minCut[j+1] = minCut[i]+1;
}
}
}
return minCut[slen];
}
}
public int minCut(String s) {
int slen = s.length();
boolean[][] palind = new boolean[slen][slen];
for(int i=slen-1;i>=0;i--)
{
for(int j=i;j<slen;j++)
{
palind[i][j] = (s.charAt(i)==s.charAt(j))&&((j-i<2)||palind[i+1][j-1]);
}
}
int[] minCut = new int[slen+1];
for(int i=0;i<slen+1;i++)
minCut[i] = i-1;
for(int i=0;i<slen;i++)
{
for(int j=i;j<slen;j++)
{
if(palind[i][j]&&minCut[i]<minCut[j+1])
{
minCut[j+1] = minCut[i]+1;
}
}
}
return minCut[slen];
}
}
0 0
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- Palindrome Partitioning II
- Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- Palindrome Partitioning II
- LetCode:Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- Clone Graph
- Palindrome Partitioning
- 2014.10.02
- 数字图像之边缘检测(1)
- 检索地理位置(GeocodeService服务)
- Palindrome Partitioning II
- Surrounded Regions
- 【异或】SOJ Find Differences
- Sum Root to Leaf Numbers
- day38,page60,total390
- Longest Consecutive Sequence
- ubuntu 下eclipse 打不开
- Word Ladder
- 各种工业以太网比较(EtherCAT,EtherNet/IP,ProfiNet,Modbus-TCP,Powerlink)