686.重复叠加字符串匹配

本文深入探讨了重复叠加字符串匹配问题的解决思路,通过分析不同情况下的头部和尾部字符串长度更新,提出了一种有效的算法实现。文章详细介绍了如何判断一个字符串B是否能通过另一个字符串A的多次重复叠加来形成,并提供了具体代码实现。

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

686.重复叠加字符串匹配

解决思路:
分几种情况去讨论;
值得注意的是时刻更新确定头部多出的字符串长度;

class Solution {
public:
    int head=0,tail=0;
    int repeatedStringMatch(string A, string B)
    {
        int times=0;
        auto pos_B=B.find(A);
        if(pos_B==string::npos)
        {
            head=-1,tail=-1;
            if(A.find(B)!=string::npos)//A完全包含B返回1
                return 1;
            else
            {
                int tmp=check(A,B);
                if(tmp!=0)
                    return tmp;
            }
            //A无论如何组合都不包含B
            return -1;
        }
        else
            head=pos_B;
        while(1)
        {
            times++;
            B.erase(pos_B,A.length());
            pos_B=B.find(A,head);
            if(pos_B!=string::npos)
                head=pos_B;//更新头部多出字符串长度
            else
                break;
        }
        if(B.length()!=0)
        {
            if(B.length()!=head)
            {
                tail=B.length()-head;
            }
            int tmp=check(A,B);
            if(tmp==-1)
                return -1;
            return times+tmp;
        }
        return times;
    }
    int check(string A,string B)
    {
        string tmp=A+A;
        if(head==-1&&tail==-1)//前置搜索
        {
            if(A.find(B)!= string::npos)
                return 1;
            if(tmp.find(B)!=string::npos)
                return 2;
            return -1;
        }
        if(head!=0&&tail!=0)
        {
            if(tmp.find(B)!=string::npos)
                if(B[head-1]==A[A.length()-1]&&B[head]==A[0])
                    return 2;
        }
        else if(head==0&&tail!=0)
        {
            if(A.find(B)!=string::npos)
                if(A[0]==B[0])
                    return 1;
        }
        else if(head!=0&&tail==0)
        {
            if(A.find(B)!=string::npos)
                if(A[A.length()-1]==B[B.length()-1])
                    return 1;
        }
        return -1;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值