leetcode Palindrome Partitioning

本文介绍了一个使用回溯算法解决字符串分割问题的方法,通过递归地判断子字符串是否为回文,并将其加入到结果集中。为了提高算法效率,文章建议预先创建一个表来记录各子字符串是否为回文的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接
这个题目主要用到了回溯算法。只能说是一个经过优化的递归回溯。如果想提高一点算法效率的话。就要先建立一个表。。表格里面存放从A,到B字符串是不是回文的。这样能够增加一点效率。

public class Solution {


    String s;
    List<List<String>> result=new LinkedList<List<String>>();
    List<String> tempResult=new LinkedList<String>();


     public List<List<String>> partition(String s) {
        this.s=s;
        help(0,s.length()-1);
        return result;

    }

    public void help(int start,int end)
    {
        if(start>end)
        {
            List<String> temp=new LinkedList<String>();
            for(String str:tempResult)
            {
                temp.add(str);
            }
            result.add(temp);
            return;
        }
        for(int i=start;i<=end;i++)
        {
            if(isPara(start, i))
            {
                tempResult.add(s.substring(start, i+1));

                help(i+1,end);
                tempResult.remove(tempResult.size()-1);
            }
        }
    }

    public boolean isPara(int start,int end)
    {
        while(start<end)
        {
            if(s.charAt(start)==s.charAt(end))
            {
                start++;
                end--;
            }
            else
            {
                return false;
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值