您的位置:首页 > 其它

LeetCode: Palindrome Partitioning 解题报告

2014-10-20 16:51 288 查看
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"]
]

[b]Solution 0:[/b]

直接用DFS 做,实际上也是可以过Leetcode的检查的。

// BUG 3: use boolean instead of Boolean.
public static boolean isPalindromeHash(String s, HashMap<String, Boolean> map) {
int len = s.length();
int left = 0;
int right = len - 1;

if (map.get(s) != null) {
return map.get(s);
}

map.put(s, true);
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
map.put(s, false);
return false;
}
left++;
right--;
}

return true;
}

// Solution 3: Use DP to determine the palindrome first.
public List<List<String>> partition(String s) {
List<List<String>> ret = new ArrayList<List<String>>();
if (s == null) {
return ret;
}

int len = s.length();

// D[i][j]: if this a palindrom for s.substring(i, j + 1).
boolean[][] D = new boolean[len][len];

for (int j = 0; j < len; j++) {
for (int i = 0; i <= j; i++) {
D[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || D[i + 1][j - 1]);
}
}

// bug: new map error.
dfs3(s, 0, new ArrayList<String>(), ret, D);
return ret;
}

public static void dfs3(String s, int index, List<String> path, List<List<String>> ret, boolean[][] D) {
int len = s.length();
if (index == len) {
ret.add(new ArrayList<String>(path));
return;
}

for (int i = index; i < len; i++) {
String sub = s.substring(index, i + 1);
if (!D[index][i]) {
continue;
}

path.add(sub);
dfs3(s, i + 1, path, ret, D);
path.remove(path.size() - 1);
}
}


View Code
Runtime: 524 ms, 实际上运行时间也没多少改善。可能是数据集大小的问题咯。

[b]GitHub Link:[/b]

Partition.java

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/Partition_2014_1229.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: