131. 分割回文串
阿新 • • 發佈:2020-07-25
給定一個字串 s,將 s 分割成一些子串,使每個子串都是迴文串。
返回 s 所有可能的分割方案。
示例:
輸入: "aab" 輸出: [ ["aa","b"], ["a","a","b"] ]
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/palindrome-partitioning
思路:
DFS的回溯演算法,如果字串的分段是迴文的就擷取片段判斷後面的
如果到最後字串已經被分解的只剩下0的長度,說明就是我們想要的部分,儲存到res中
class Solution { public List<List<String>> partition(String s){ List<List<String>> res = new LinkedList<>(); List<String> path = new ArrayList<>(); dfs(path,res,s); return res; } private void dfs(List<String> path, List<List<String>> res, String s) { if (s.length() == 0){ res.add(new ArrayList<>(path)); return; } for (int i = 0; i < s.length(); i++) { if (isPalindrome(s,0,i)){ path.add(s.substring(0,i + 1)); dfs(path,res,s.substring(i + 1)); path.remove(path.size() - 1); } } }//判斷是否迴文 public boolean isPalindrome(String s,int begin,int end){ while (begin < end){ if (s.charAt(begin) == s.charAt(end)){ begin++; end--; }else { return false; } } return true; } }