686.重复叠加字符串匹配

版权声明:孔庆鑫 https://blog.csdn.net/kongqingxin12/article/details/85091283

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;

    }
};

猜你喜欢

转载自blog.csdn.net/kongqingxin12/article/details/85091283