[leetcode]686. Repeated String Match
Analysis
微博第一次中奖~—— [嘻嘻,耶~]
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”).
主要用到了AA.find(B) != string::npos
Implement
方法一:(天知道这个while循环的条件我纠结了多久!!!)
class Solution {
public:
int repeatedStringMatch(string A, string B) {
int res = 1;
int lenA = A.length();
int lenB = B.length();
int len = 0;
string AA = A;
while(len <= lenB+lenA){
if(AA.find(B) != string::npos)
return res;
AA += A;
res++;
len += lenA;
}
return -1;
}
};
方法二:
class Solution {
public:
int repeatedStringMatch(string A, string B) {
int res = 1;
int lenA = A.length();
int lenB = B.length();
string AA = A;
while(AA.length() < lenB){
AA += A;
res++;
}
if(AA.find(B) != string::npos)
return res;
AA += A;
res++;
if(AA.find(B) != string::npos)
return res;
return -1;
}
};