题目:给定一个字符串s,要求划分串s使得得到的每一个子串都是一个回文串(即字符串从中间划分,前、后字符为镜像),结果返回所有可能的划分。
例如:给定s=“ababc”,返回
[
[“aba”,“b”, “c”],
[“a”,“bab”, “c”],
[“a”,“b”, “a”, “b”, “c”]
]
才发现这是LeetCode上的题目,链接在此。
主要是深度优先搜索和回溯法的运用,Java代码如下。
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> list = new ArrayList<String>();
DFS(s, 0, list, result);
return result;
}
public void DFS(String s, int pos, List<String> list, List<List<String>> result) {
if (pos == s.length()) {
result.add(new ArrayList<String>(list));
} else {
for (int i = pos; i < s.length(); i++) {
if (isPal(s, pos, i)) {
list.add(s.substring(pos, i + 1));
DFS(s, i + 1, list, result);
list.remove(list.size() - 1);
}
}
}
}
public boolean isPal(String s, int begin, int end) {
while (begin < end) {
if (s.charAt(begin++) != s.charAt(end--))
return false;
}
return true;
}
}