131. Palindrome Partitioning

亦凉 2022-02-15 12:35 317阅读 0赞
  1. Given a string s, partition s such that every substring of the partition is a palindrome.
  2. Return all possible palindrome partitioning of s.
  3. Example:
  4. Input: "aab"
  5. Output:
  6. [
  7. ["aa","b"],
  8. ["a","a","b"]
  9. ]

本题又是一个回溯的题目。

  1. public List<List<String>> partition(String s) {
  2. List<List<String>> ans = new ArrayList<>();
  3. if(s.length() == 0) return ans;
  4. backTracking(s, new ArrayList<>(), ans);
  5. return ans;
  6. }
  7. private void backTracking(String s, List<String> current, List<List<String>> ans) {
  8. if(s.length() == 0) {
  9. ans.add(new ArrayList<>(current));
  10. return;
  11. }
  12. for(int i = 0; i < s.length(); ++i) {
  13. String sub = s.substring(0, i + 1);
  14. if(isAPalindrome(sub)) {
  15. current.add(sub);
  16. backTracking(s.substring(i + 1), current, ans);
  17. current.remove(current.size() - 1);
  18. }
  19. }
  20. }
  21. private boolean isAPalindrome(String s) {
  22. for(int i = 0; i < s.length() / 2; ++i) {
  23. if(s.charAt(i) != s.charAt(s.length() - i - 1)) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }

发表评论

表情:
评论列表 (有 0 条评论,317人围观)

还没有评论,来说两句吧...

相关阅读