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, int end){ for (int i = startIndex,j = end; i < j; i++, j--){ if (s.charAt(i) != s.charAt(j)){ return false; } } return true; } }
93、复原IP地址
基本思想:
回溯算法
具体实现:
代码:
class Solution { List<String> result = new ArrayList<>(); public List<String> restoreIpAddresses(String s) { if (s.length() > 12) return result; backTrack(s, 0, 0); return result; } private void backTrack(String s, int startIndex, int pointNum){ if (pointNum == 3){ if(isValid(s, startIndex,s.length()-1)){ result.add(s); } return; } for (int i = startIndex; i < s.length(); i++){ if (isValid(s,startIndex,i)){ s = s.substring(0, i + 1) + "." + s.substring(i + 1); pointNum++; backTrack(s, i + 2, pointNum); pointNum--; s = s.substring(0,i+1) + s.substring(i + 2); }else{ break; } } } private Boolean isValid(String s, int start, int end){ if (start > end){ return false; } if (s.charAt(start) == '0' && start != end){ return false; } int num = 0; for (int i = start; i <= end; i++){ if (s.charAt(i) > '9' || s.charAt(i) < '0'){ return false; } num = num * 10 + (s.charAt(i) - '0'); if (num > 255){ return false; } } return true; } }