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"]
]
Solution 0:
直接用DFS 做,实际上也是可以过Leetcode的检查的。
1 public List<List<String>> partition(String s) { 2 List<List<String>> ret = new ArrayList<List<String>>(); 3 if (s == null) { 4 return ret; 5 } 6 7 dfs(s, 0, new ArrayList<String>(), ret); 8 return ret; 9 } 10 11 public static void dfs(String s, int index, List<String> path, List<List<String>> ret) { 12 int len = s.length(); 13 if (index == len) { 14 ret.add(new ArrayList<String>(path)); 15 return; 16 } 17 18 for (int i = index; i < len; i++) { 19 String sub = s.substring(index, i + 1); 20 if (!isPalindrome(sub)) { 21 continue; 22 } 23 24 path.add(sub); 25 dfs(s, i + 1, path, ret); 26 path.remove(path.size() - 1); 27 } 28 } 29 30 public static boolean isPalindrome(String s) { 31 int len = s.length(); 32 int left = 0; 33 int right = len - 1; 34 35 while (left < right) { 36 if (s.charAt(left) != s.charAt(right)) { 37 return false; 38 } 39 left++; 40 right--; 41 } 42 43 return true; 44 }