回文串分割,判断一个字符串是否能分割为三个子串,且满足三个子串皆为回文串

本文介绍了一种判断字符串是否能通过三次分割形成四个回文子串的方法。算法使用双指针从两端向中间搜索可能的分割点,并验证分割后的子串是否为回文。此方法适用于需要高效解决字符串回文问题的场景。

在这里插入图片描述
在这里插入图片描述

class Solution {
    public boolean checkPartitioning(String s) {
        int len = s.length();
        int head = 0;
        int tail = len-1;
        int prehead = head;
        int behead = head;

        if(checkApart(head,tail,s))
            return true;

        while(head < tail)
        {
            prehead = head;
            do
            {
                head++;
            }while(head < tail && !checkHuiWen(s.substring(0,head+1)));

            behead = head;
            if(head < tail)
                if(checkApart(head,tail,s))
                    return true;

            head = prehead;
            do
            {
                tail--;
            }while(head < tail &&  !checkHuiWen(s.substring(tail,s.length())));

            if(head < tail)
                if(checkApart(head,tail,s))
                    return true;
            
            head = behead;
            if(head < tail)
                if(checkApart(head,tail,s))
                    return true;
        }

        return false;
    }

    public boolean checkHuiWen(String str)
    {
        int n = str.length();
        for(int i=0;i<n/2;i++)
            if(str.charAt(i) != str.charAt(n-i-1))
                return false;
        return true;
    }

    public boolean checkApart(int head,int tail, String s)
    {
        return checkHuiWen(s.substring(0,head+1)) && checkHuiWen(s.substring(head+1,tail)) && checkHuiWen(s.substring(tail,s.length()));
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值