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"] ]
解题思路:
这种题目一看就是DFS的题,中间用到一个 Valid Palindrome 的方法,判断一个string是不是palindrome。
对于每个位置start,取字符串的可能都是从start开始一直到结尾,所以要判断它是不是palindrome,是的话就加入current。对于下面的字符串继续DFS。到结尾了,回溯。
public class Solution { public List<List<String>> partition(String s) { List<List<String>> result = new LinkedList<List<String>>(); if(s.length() == 0) { return result; } dfs(s, result, new LinkedList<String>(), 0); return result; } public void dfs(String s, List<List<String>> result, LinkedList<String> current, int start) { if(current.size() > 0 && !isPalindrome(current.getLast())) { return; } if(start == s.length()) { result.add(new LinkedList(current)); } for(int i = 1; i < s.length() - start + 1; i++) { current.add(s.substring(start, start + i)); dfs(s, result, current, start + i); current.remove(current.size() - 1); } } public boolean isPalindrome(String s) { if(s.length() == 0) { return true; } int start = 0, end = s.length() - 1; while(start < end) { if(s.charAt(start) != s.charAt(end)){ return false; } start++; end--; } return true; } }
//20180928
class Solution { public List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<List<String>>(); if (s == null || s.length() == 0) { return res; } List<String> cur = new ArrayList<String>(); dfs(s, cur, res, 0, 0); return res; } public void dfs(String s, List<String> cur, List<List<String>> res, int start, int sumLength) { if (sumLength == s.length()) { res.add(new ArrayList<String>(cur)); return; } for (int i = start; i < s.length(); i++) { String sub = s.substring(start, i + 1); if (!isPalindrome(sub)) { continue; } cur.add(sub); dfs(s, cur, res, i + 1, sumLength + sub.length()); cur.remove(cur.size() - 1); } } public boolean isPalindrome(String s) { if (s == null || s.length() == 0 || s.length() == 1) { return true; } int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; } }