From : 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"] ]
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> ans;
if(s == "") return ans;
vector<string> cur;
find(ans, cur, s, 0, s.size()-1);
return ans;
}
void find(vector<vector<string>>& ans, vector<string>& cur, string s, int start, int end) {
if(start > end) {ans.push_back(cur); return; }
for(int i=start; i<=end; i++) {
if(isPalindrome(s, start, i)) {
cur.push_back(s.substr(start, i-start+1));
find(ans, cur, s, i+1, end);
cur.pop_back();
}
}
}
bool isPalindrome(string s, int start, int end) {
while(start < end) {
if(s[start] != s[end]) return false;
start++;
end--;
}
return true;
}
};
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> ans = new ArrayList<List<String>>();
if (s != null && !"".equals(s)) {
find(s, 0, s.length() - 1, new LinkedList<String>(), ans);
}
return ans;
}
private void find(String s, int st, int ed, LinkedList<String> fd, List<List<String>> ans) {
if (st > ed) {
ans.add(new ArrayList<String>(fd));
return;
}
for (int i = st; i <= ed; ++i) {
if (valid(s, st, i)) {
String me = s.substring(st, i + 1);
fd.add(me);
find(s, i + 1, ed, fd, ans);
fd.removeLast();
}
}
}
private boolean valid(String s, int i, int j) {
while (i < j) {
if (s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}