先搞清楚題目, 題目的意思是問, a要複製多少次, b才會變成a的substring
首先, a的size假設小於b, 那肯定是無法的, 所以我們複製到a size至少等於b
然後用find在a找b, 找不到, 有可能是有一種case “abc” “cab”, 這種情況我們再追加複製一次, 在判別一次, 在沒結果就沒了
class Solution {
public:
int repeatedStringMatch(string a, string b) {
int n1 = a.size();
int n2 = b.size();
int count = 1;
string t = a;
while(t.size() < n2){
t += a;
count++;
}
if(t.find(b) != string::npos)
return count;
t+= a;
if(t.find(b) !=string::npos) return count + 1;
else return -1;
}
};
另一種方法就是當a小於b時, 總共最小要複製 b/ a + 1次, 這邊我們多加一個1, 就是上面的特例, 所以我們最多就是複製b /a + 2就應該要能判斷了
class Solution {
public:
int repeatedStringMatch(string a, string b) {
int n1 = a.size();
int n2 = b.size();
string t = a;for(int i = 1; i <= n2/n1 + 2;i++){
if(t.find(b) != string::npos)return i;
t+=a;
}
return -1;
}
};