131. Palindrome Partitioning
简直开心,一遍通过,时间不是特别好,我觉得是isPalindrome用的是StirngBuilder方法不是数学方法的原因
不过很开心!!
1 public List<List<String>> partition(String s) { 2 List<List<String>> res = new ArrayList<List<String>>(); 3 if(s == null || s.length() == 0) { 4 return res; 5 } 6 helper(res, s, 0, new ArrayList<String>()); 7 return res; 8 } 9 10 private void helper(List<List<String>> res, String s, int start, List<String> curStr) { 11 int len = s.length(); 12 if(start == len) { 13 res.add(new ArrayList<String>(curStr)); 14 return; 15 } 16 for(int i = 1; i + start <= len; i++) { 17 String sub = s.substring(start, i + start); 18 if(isPalindrome(sub)) { 19 curStr.add(sub); 20 helper(res, s, start + i, curStr); 21 curStr.remove(curStr.size() - 1); 22 } 23 } 24 } 25 26 private boolean isPalindrome(String s) { 27 if(s == null || s.length() == 0) { 28 return true; 29 } 30 StringBuilder sb = new StringBuilder(s); 31 String rev = sb.reverse().toString(); 32 return s.equals(rev); 33 }