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 =
Return
"aab"
,Return
[ ["aa","b"], ["a","a","b"] ]
注意: 当int n是s的length时候返回
public class Solution { public ArrayList<ArrayList<String>> partition(String s) { ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); ArrayList<String> tem = new ArrayList<String>(); if (s.length() == 0 || s == null){ return result; } dfs(result, tem, s, 0); return result; } public void dfs(ArrayList<ArrayList<String>> result, ArrayList<String> tem, String s, int n){ if (n == s.length()){ result.add(new ArrayList<String>(tem)); return; } for (int i = n; i < s.length(); i++){ String str = s.substring(n, i + 1); if (isPalindrome(str)){ tem.add(str); dfs(result, tem, s, i + 1); tem.remove(tem.size() - 1); } } } public boolean isPalindrome(String str){ int n = 0; int k = str.length(); while (n < k){ if (str.charAt(n) != str.charAt(k - 1)){ return false; } n++; k--; } return true; } }
没有评论:
发表评论