LeetCode 131. 分割回文串

题目:

131. 分割回文串

题解:

  1. 暴力搜索字符串 s 的所以子串合集
  2. 判断每个子串是否都是回文串

回文字符串判断方法:双指针法。双指针依次指向字符串头、尾,从两头依次向中间移动指针直到相遇,如果两个指针移动过程中指向的字符始终都是一样的,那么该字符串就是回文字符串。

class Solution {
    private List> resultList = new ArrayList<>();
    private LinkedList list = new LinkedList<>();

    public List> partition(String s) {
        dfsForSplit(s, 0);

        Iterator> iterator = resultList.iterator();
        while (iterator.hasNext()) {
            List next = iterator.next();
            boolean isPalindromic = true;
            for (int i = 0; i < next.size() && isPalindromic; i++) {
                isPalindromic = isPalindromic(next.get(i));
            }

            if (!isPalindromic) {
                iterator.remove();
            }
        }

        return resultList;
    }

    private void dfsForSplit(String s, int start) {
        if (s == null || s.length() == 0) {
            resultList.add(new ArrayList<>(list));
            return;
        }

        for (int i = start; i < s.length(); i++) {
            String prefix = s.substring(start, i+1);
            list.add(prefix);
            dfsForSplit(s.substring(i+1), start);
            list.removeLast();
        }
    }

    private boolean isPalindromic(String s) {
        int start = 0;
        int end = s.length() - 1;
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }

            start++;
            end--;
        }
        return true;
    }
}

剪枝:

如果当前分割字符串不是回文字符串,那么就不必再继续搜索了,直接跳过,进行下一次分割。

class Solution {
    private List> resultList = new ArrayList<>();
    private LinkedList list = new LinkedList<>();

    public List> partition(String s) {
        dfsForSplit(s, 0);
        return resultList;
    }

    private void dfsForSplit(String s, int start) {
        if (s == null || s.length() == 0) {
            resultList.add(new ArrayList<>(list));
            return;
        }

        for (int i = start; i < s.length(); i++) {
            String prefix = s.substring(start, i+1);
            if (!isPalindromic(prefix)) {
                continue;
            }

            list.add(prefix);
            dfsForSplit(s.substring(i+1), start);
            list.removeLast();
        }
    }

    private boolean isPalindromic(String s) {
        int start = 0;
        int end = s.length() - 1;
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }

            start++;
            end--;
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,回溯,回文)