您的位置:首页 > 其它

Leetcode:Palindrome Partitioning & Palindrome Partitioning II

2017-12-03 21:22 435 查看

Palindrome Partitioning

URL

https://leetcode.com/problems/palindrome-partitioning/description/

描述

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = “aab”,

Return

[

[“aa”,”b”],

[“a”,”a”,”b”]

]

解题思路

如果s.subString(i,j)为回文字符串,则s.subString(i+1,j-1)也是回文字符串,所以基于这个特征,我们可以先对s做一个预处理。

dp[i,j] = if(s[i]==s[j) then if(dp[i+1,j-1]) -> true;

else ->false

之后就是一个简单的DFS即可。下面给出代码示例:

List<List<String>> res = new ArrayList<>();
boolean[][] dp;
public List<List<String>> partition(String s) {
int len = s.length();
dp = new boolean[len+1][len+1];
for(int i=0;i<=s.length();i++){
dp[i][i] = true;
dp[0][i] = true;
dp[i][0] = true;
}

for(int i=1;i<=s.length();i++){
for(int j=1;j<i;j++){
if(s.charAt(i-1)==s.charAt(j-1)&&(dp[j+1][i-1]|| j+1 > i-1)){
dp[j][i] = true;
}
}
}
dfs(s,0,new ArrayList<>());
return res;
}

void dfs(String s, int index, List<String> path){
if(index == s.length()){
res.add(new ArrayList<String>(path));
}

for(int i = index;i<s.length();i++){
if(dp[index+1][i+1]){
path.add(s.substring(
4000
index,i+1));
dfs(s,i+1,path);
path.remove(path.size()-1);
}
}
}


Palindrome Partitioning II

url

https://leetcode.com/problems/palindrome-partitioning-ii/description/

描述

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.

解题思路

在Palindrome Partitioning用到的最优解结构这里还需要用到,另外我们还需要用到的一个结构是:

dp2[i] = for(j:i->1) if(dp[j,i]) then dp2[i] = min(dp2[i],dp2[j]+1)

代码示例

class Solution {
boolean[][] dp;
int[] dp2;

public int minCut(String s) {
int len = s.length();
dp = new boolean[len+1][len+1];
dp2 = new int[len+1];
for(int i=0;i<=s.length();i++){
dp[i][i] = true;
dp[0][i] = true;
dp[i][0] = true;
}

for(int i=1;i<=len;i++){
for(int j=1;j<i;j++){
if(s.charAt(i-1)==s.charAt(j-1)&&(dp[j+1][i-1]|| j+1 > i-1)){
dp[j][i] = true;
}
}
}

for(int i = 1;i<=len;i++){
dp2[i] = dp2[i-1]+1;
for(int j=i-1;j>=1;j--){
if(dp[j][i]){
dp2[i] = Math.min(dp2[i],dp2[j-1]+1);
}
}
}
return dp2[len]-1;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: