【兩次過】Lintcode 136. 分割回文串
阿新 • • 發佈:2018-12-20
給定一個字串s,將s分割成一些子串,使每個子串都是迴文串。
返回s所有可能的迴文串分割方案。
樣例
給出 s = "aab"
,返回
[
["aa", "b"],
["a", "a", "b"]
]
解題思路:
DFS
public class Solution { /* * @param s: A string * @return: A list of lists of string */ public List<List<String>> partition(String s) { // write your code here List<List<String>> res = new ArrayList<>(); if(s == null || s.length() == 0) return res; dfs(s, 0, new ArrayList<String>(), res); return res; } private void dfs(String s, int startIndex, List<String> temp, List<List<String>> res){ if(startIndex == s.length()) res.add(new ArrayList<String>(temp)); for(int i=startIndex; i<s.length(); i++){ String subString = s.substring(startIndex, i+1); if(!isPalindrome(subString)) continue; temp.add(subString); dfs(s, i+1, temp, res); temp.remove(temp.size()-1); } } private boolean isPalindrome(String s){ int i = 0; int j = s.length() - 1; while(i < j){ if(s.charAt(i++) != s.charAt(j--)) return false; } return true; } }