[leetcode] 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"] ]
https://oj.leetcode.com/problems/palindrome-partitioning/
思路:因为要返回所有的结果,dfs来做。
public 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> tmp = new ArrayList<String>(); part(res, tmp, s); return res; } private void part(List<List<String>> res, List<String> tmp, String s) { if ("".equals(s)) { res.add(new ArrayList(tmp)); return; } for (int i = 1; i <= s.length(); i++) { String pre = s.substring(0, i); if (isPalin(pre)) { tmp.add(pre); part(res, tmp, s.substring(i, s.length())); tmp.remove(tmp.size()-1); } } } private boolean isPalin(String s) { if (s == null) return false; if (s.length() <= 1) return true; int len = s.length(); int i = 0, j = len - 1; while (i < j) { if (s.charAt(i++) != s.charAt(j--)) return false; } return true; } public static void main(String[] args) { System.out.println(new Solution().partition("aab")); } }
参考:
http://www.tuicool.com/articles/jmQ3uu
http://blog.csdn.net/worldwindjp/article/details/22066307