其他分享
首页 > 其他分享> > 力扣131. 分割回文串

力扣131. 分割回文串

作者:互联网

这一个题要设置两个全局变量(当然其实不设也是可以的),即List<List> res 和 List item。注意这里我用了List item就是不对的,必须用Deque item,不然就AC不了。
AC代码如下:注释部分是源代码

class Solution {
    List<List<String>> res =new ArrayList<>();
    Deque<String> item = new LinkedList<>();//List<String> item = new LinkedList<>();
    
    public List<List<String>> partition(String s) {
        backTracking(s, 0);
        return res;
    }
    public boolean isPalindrome(char[] str, int start, int end){
        while(start < end){
            if(str[start] != str[end]) return false;
            start++;
            end--;
        }
        return true;
    }
    public void backTracking(String s, int start){
        if(start == s.length()){
            res.add(new ArrayList<>(item));
            return;
        }
        for(int i = start; i < s.length(); i++){
            String str = s.substring(start, i + 1);
            if(isPalindrome(s.toCharArray(), start, i)){
                item.addLast(str);//item.add(str);
                backTracking(s, i + 1);
                item.removeLast();//item.remove(str);
            }else{
                continue;
            }
        }
    }
}

出错的用例如下:
可以看到出错从第二个List开始,主要是顺序不一致
导致顺序不一致的原因就是,item里有多个重复的字串,比如第一个item里有三个c,当回溯时要删除的c应该是最后一个c,但是List的remove()函数会从头开始搜索删除,所以删除的是第一个c,这就导致了item里的顺序乱了,但是内容还是一样的,所有子字符串的顺序就不是cbbbcc了。

标签:return,start,res,List,力扣,item,131,str,回文
来源: https://blog.csdn.net/xsybg/article/details/122782467