力扣131題(分割回文串)
阿新 • • 發佈:2021-10-15
131、分割回文串
基本思想:
回溯演算法
具體實現:
程式碼:
class Solution { List<List<String>> lists = new ArrayList<>(); Deque<String> deque = new LinkedList<>(); public List<List<String>> partition(String s) { backTracking(s, 0); return lists; }private void backTracking(String s, int startIndex){ //startIndex就是分割處 if(startIndex >= s.length()){ lists.add(new ArrayList(deque)); return; } for (int i = startIndex; i < s.length(); i++){ //判斷[startIndex,i]是否迴文 if (isPalindrome(s, startIndex, i)){ String str= s.substring(startIndex, i+1); deque.addLast(str); } else{ continue; } backTracking(s, i + 1);//尋找i+1為起始位置的子串 deque.removeLast(); } } private boolean isPalindrome(String s, int startIndex, intend){ for (int i = startIndex,j = end; i < j; i++, j--){ if (s.charAt(i) != s.charAt(j)){ return false; } } return true; } }