您的位置:首页 > 其它

LeetCode 131. Palindrome Partitioning(回文分区)

2016-05-27 00:25 483 查看
原题网址:https://leetcode.com/problems/palindrome-partitioning/

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"]
]


方法:深度优先搜索。

public class Solution {
private List<List<String>> results = new ArrayList<>();
private boolean[][] palindrome;
private void find(String s, List<String> partition, int from) {
if (from == s.length()) {
List<String> result = new ArrayList<>();
result.addAll(partition);
results.add(result);
return;
}
for(int i=0; from+i<s.length(); i++) {
if (!palindrome[i][from]) continue;
partition.add(s.substring(from, from+i+1));
find(s, partition, from+i+1);
partition.remove(partition.size()-1);
}
}
public List<List<String>> partition(String s) {
if (null == s || "".equals(s)) return results;
palindrome = new boolean[s.length()][s.length()];
for(int i=0; i<s.length(); i++) {
for(int j=0; j+i<s.length(); j++) {
if (i==0) {
palindrome[i][j] = true;
} else if (i==1) {
if (s.charAt(j) == s.charAt(j+i)) {
palindrome[i][j] = true;
} else {
palindrome[i][j] = false;
}
} else {
if (palindrome[i-2][j+1] && s.charAt(j) == s.charAt(j+i)) {
palindrome[i][j] = true;
} else {
palindrome[i][j] = false;
}
}
}
}
find(s, new ArrayList<>(), 0);
return results;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: