DP動態規劃專題四 :LeetCode 132. Palindrome Partitioning
阿新 • • 發佈:2018-12-30
LeetCode 132. 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.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
思路還是一樣,n的答案依賴於0~n-1的答案
public List<List<String>> partition(String s) { List<List<List<String>>> allResult = new ArrayList<>(); List<List<String>> res = new ArrayList<>(); if (s.length() == 0) return res; List<String> l = new ArrayList<>(); l.add(s.substring(0,1)); res.add(l); allResult.add(res); for (int i = 1; i < s.length(); i++) { List<List<String>> curRes = new ArrayList<>(); for (int p = 0; p <= i; p++) { String curs = s.substring(p,i+1); if (isPalindrome(curs)) { List<List<String>> pre = new ArrayList<>(); List<String> a = new ArrayList<>(); pre.add(a); if (p != 0) pre = allResult.get(p-1); for (List<String> ll : pre) { List<String> lll = new ArrayList<>(ll); lll.add(curs); curRes.add(lll); } } } allResult.add(curRes); } List<List<String>> result = allResult.get(allResult.size() - 1); return result; } private boolean isPalindrome(String s) { if (s.length() <= 1) return true; int l = 0; int r = s.length() - 1; while (l < r) { if (s.charAt(l++) != s.charAt(r--)) { return false; } } return true; }