LeetCode131. 分割回文串

☆☆☆思路1:递归+回溯

思路2:动态规划。 M

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        dfs(s, 0, new ArrayList<>(), res);
        return res;
    }
    private void dfs(String s, int start, List<String> list, List<List<String>> res) {
        if (start == s.length()) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            String temp = s.substring(start, i + 1);
            if (isPalindrome(temp)) {
                list.add(temp);
                dfs(s, i + 1, list, res);
                list.remove(list.size() - 1);
            }
        }
    }
    // 判断是否是回文串
    private boolean isPalindrome(String s) {
        if (s == null || s.length() <= 1) return true;
        int left = 0, right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left ++;
            right --;
        }
        return true;
    }
}

 

posted @ 2020-12-26 21:05  不学无墅_NKer  阅读(55)  评论(0编辑  收藏  举报