LeetCode 131-分割回文串

在这里插入图片描述
思路:搜索分割点,每次判断当前分割点喝上一个分割点之间的数据是否为回文串,如果是,就继续搜索下一个。
(来实验室工作的第二天,加油!)

class Solution {
    String str;
    int len;
    LinkedList<LinkedList<Integer>> list = new LinkedList<>();

    public boolean check(String s){
        // 判断s是否是回文字符串
        if(s.length()==0 || s.length()==1){
            return true;
        }
        return s.charAt(0)==s.charAt(s.length()-1) && check(s.substring(1,s.length()-1));
    }
    
    public void dfs(int splitIndex, LinkedList<Integer> tmp){
        if(splitIndex==len+1){
            list.add(new LinkedList<>(tmp));
            return;
        }

        for(int i=splitIndex; i<len+1;i++){
            int lastSplitIndex = 0;
            if(tmp.size() != 0){
                lastSplitIndex = tmp.get(tmp.size()-1);
            }
            String subStr = str.substring(lastSplitIndex, i);
            if(check(subStr)){
                tmp.add(i);
                dfs(i+1, tmp);
                tmp.removeLast();
            }
        }

        return;
    }

    public List<List<String>> partition(String s) {
        // 遍历切割点即可
        this.str = s;
        this.len = str.length();

        LinkedList<Integer> tmp = new LinkedList<>();
        dfs(1, tmp);    //遍历切割点

        // 将分割点转为字符串
        List<List<String>> res = new LinkedList<>();
        for(LinkedList<Integer> item: list){
            List<String> res_item = new LinkedList<>();
            int lastSplitIndex = 0;
            for(int currentSplitIndex : item){
                String subStr = str.substring(lastSplitIndex, currentSplitIndex);
                res_item.add(subStr);
                lastSplitIndex = currentSplitIndex;
            }
            res.add(res_item);
        }

        return res;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小吴同学GOGOGO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值