leetcode hot100分割回文串

leetcode hot100分割回文串_第1张图片
本题是要求将给定的字符串进行分割,返回分割的回文串子串。那么我们以下图假设
leetcode hot100分割回文串_第2张图片
由此可以看出,这就是一个组合问题,所以可以根据回溯算法来解决。同时,我们应该知道,在本题中,树的宽度是由给定的字符串的长度决定的,需要用for循环来进行遍历,递归用来纵向遍历,来进行更细粒度的切割。

那么我们需要确定参数,我们需要字符串S,然后还需要一个开始切割位置的索引;

然后,我们需要判断终止条件,也就是,当我们这个切割的索引,走到了最后,也就是上图中,aab的位置,注意,必须得走到b之后,走到b的话说明,b还是可以切割的。那么就是startIndex==s.length()。我们将此时切割的结果直接存入到保存结果的二维数组中即可。

然后,我们进行单层递归的逻辑,也就是,切割的逻辑(纵向递归)。首先我们需要判断,我们当前切割的字符串是不是回文串,也就需要一个函数来判断,如果是,那么我们需要记录下来,如果不是,则直接跳过该次循环。注意,这里切割是用的for循环,startIndex是起点,i是终点。

然后直接进行下一次递归,递归开始的索引应该是上一次递归切割之后的线,也就是应该从i+1开始。

注意,s.substring(startIndex,i),切割字符串的区间是左闭右开,也就是包括startIndex索引,不包括i+1位置上的字符。所以此时的区间是[startIndex,i]。

class Solution {
    List> lists = new ArrayList<>();
    Deque deque = new LinkedList<>();

    public List> partition(String s) {
        backTracking(s, 0);
        return lists;
    }

    private void backTracking(String s, int startIndex) {
        //如果起始位置大于s的大小,说明找到了一组分割方案
        if (startIndex == s.length()) {
            lists.add(new ArrayList(deque));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            //如果是回文子串,则记录
            if (isPalindrome(s, startIndex, i)) {
                String str = s.substring(startIndex, i + 1);
                deque.addLast(str);
            } else {
                continue;
            }
            //起始位置后移,保证不重复
            backTracking(s, 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;
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)