LeetCode刷题笔记--686. Repeated String Match

686. Repeated String Match

Easy

443419FavoriteShare

Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab".

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:
The length of A and B will be between 1 and 10000.

注意find()的应用,另外while(C.length()<B.length())这里最开始我写反了,写成>,调了一会儿才发现。

class Solution {
public:
    int repeatedStringMatch(string A, string B) {
        string C="";
        int ans=0;
        while(C.length()<B.length())
        {
            C+=A;
            ans++;
        }
        if(C.find(B)!=-1)
        {
            return ans;
        }
        // else
        // {
            C+=A;
            ans++;
            if(C.find(B)!=-1)
            {
                return ans;
            }
            else return -1;
        // }
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/87796428