
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: “aab”
Output:
1 2 3 4
|
[ ["aa","b"], ["a","a","b"] ]
|
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
public List<List<String>> partition(String s) { List<List<String>> result = new ArrayList<>();
partitionHelper(result, new ArrayList<>(), s, 0);
return result; }
private void (List<List<String>> result, List<String> palindrome, String s, int idx) { if (idx == s.length()) { result.add(new ArrayList<>(palindrome)); return; } for (int i = idx; i < s.length(); i++) { if (isPalindrome(s, idx, i)) { palindrome.add(s.substring(idx, i + 1)); partitionHelper(result, palindrome, s, i + 1); palindrome.remove(palindrome.size() - 1); } } }
private boolean isPalindrome(String s, int start, int end) { while (start < end) { if (s.charAt(start) != s.charAt(end)) return false;
start++; end--; }
return true; }
|
近期评论