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>> result; private List<String> ret; public List<List<String>> partition(String s) { // Backtracking problem result = new LinkedList<>(); int n = s.length(); if (n == 0) return result; ret = new LinkedList<>(); backTracking(s, 0); return result; } private void backTracking(String s, int cnt) { if (cnt == s.length()) { // Note: We should allocate new memory for ret because it is changable. List<String> retCopy = new LinkedList<>(ret); result.add(retCopy); return; } else { for (int i = cnt; i < s.length(); i++) { String str = s.substring(cnt, i+1); if (place(str)) { ret.add(str); backTracking(s, i+1); ret.remove(ret.size()-1); } } } } // Verify if it is palindrome string or not private boolean place(String s) { // Note: Single character is also palindrome string int n = s.length(); for (int i = 0; i < n/2; i++) if (s.charAt(i) != s.charAt(n-i-1)) return false; return true; } }
No comments:
Post a Comment