Skip to content

Commit ca1c5dc

Browse files
author
applewjg
committed
Palindrome Partition I && II
Change-Id: I30f8b3147f6a89739508c58e13c78347a3ae0dc1
1 parent 0d217c6 commit ca1c5dc

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

PalindromePartitioning.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 20, 2015
4+
Problem: Palindrome Partitioning
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/palindrome-partitioning/
7+
Notes:
8+
Given a string s, partition s such that every substring of the partition is a palindrome.
9+
Return all possible palindrome partitioning of s.
10+
For example, given s = "aab",
11+
Return
12+
[
13+
["aa","b"],
14+
["a","a","b"]
15+
]
16+
17+
Solution: ...
18+
*/
19+
20+
public class Solution {
21+
public List<List<String>> partition(String s) {
22+
List<List<String>> res = new ArrayList<List<String>>();
23+
int n = s.length();
24+
boolean[][] dp = new boolean[n][n];
25+
for (int i = n - 1; i >= 0; --i) {
26+
for (int j = i; j < n; ++j) {
27+
dp[i][j]=(s.charAt(i)==s.charAt(j))&&(j<i+2||dp[i+1][j-1]);
28+
}
29+
}
30+
ArrayList<String> path = new ArrayList<String>();
31+
dfs(s, dp, 0, path, res);
32+
return res;
33+
}
34+
public void dfs(String s, boolean[][] dp, int start, ArrayList<String> path, List<List<String>> res) {
35+
if (s.length() == start) {
36+
res.add(new ArrayList<String>(path));
37+
return;
38+
}
39+
for (int i = start; i < s.length(); ++i) {
40+
if (dp[start][i] == false) continue;
41+
path.add(s.substring(start,i+1));
42+
dfs(s, dp, i+1,path,res);
43+
path.remove(path.size()-1);
44+
}
45+
}
46+
}

PalindromePartitioningII.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 23, 2015
4+
Problem: Palindrome Partitioning II
5+
Difficulty: Hard
6+
Source: https://oj.leetcode.com/problems/palindrome-partitioning-ii/
7+
Notes:
8+
Given a string s, partition s such that every substring of the partition is a palindrome.
9+
Return the minimum cuts needed for a palindrome partitioning of s.
10+
For example, given s = "aab",
11+
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
12+
13+
Solution: dp.
14+
*/
15+
public class Solution {
16+
public int minCut(String s) {
17+
int n = s.length();
18+
int[] dp = new int[n+1];
19+
dp[n] = -1;
20+
boolean[][] isP = new boolean[n][n];
21+
for (int i = n - 1; i >= 0; --i) {
22+
dp[i] = n - 1 - i;
23+
for (int j = i; j < n; ++j) {
24+
if (s.charAt(i) == s.charAt(j) && (j < i + 2 || isP[i+1][j-1])) isP[i][j] = true;
25+
if (isP[i][j] == true) {
26+
dp[i] = Math.min(dp[i], 1 + dp[j+1]);
27+
}
28+
}
29+
}
30+
return dp[0];
31+
}
32+
}

0 commit comments

Comments
 (0)