1.题目
给定两个字符串 A 和 B, 寻找重复叠加字符串A的最小次数,使得字符串B成为叠加后的字符串A的子串,如果不存在则返回 -1。
举个例子,A = “abcd”,B = “cdabcdab”。
答案为 3, 因为 A 重复叠加三遍后为 “abcdabcdabcd”,此时 B 是其子串;A 重复叠加两遍后为"abcdabcd",B 并不是其子串。
注意:
A 与 B 字符串的长度在1和10000区间范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/repeated-string-match
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
class Solution {
public:int repeatedStringMatch(string A, string B) {int count = 1, i;vector<int> startP;for(i = 0; i < A.size(); ++i)if(A[i] == B[0])//找头startP.push_back(i);//A可能匹配的地方string str(A), temp;for(int i : startP)//对每个可能匹配的地方,遍历{while(str.size()-i < B.size())//剩余的长度要满足B的长度{str.append(A);count++;}temp = str.substr(i,B.size());if(temp == B)return count;}return -1;}
};
A[AA…AA]A,[ ]内表示的是B
class Solution {
public:int repeatedStringMatch(string A, string B) {string str(A);int count = 1;while(str.size() < B.size()) {str.append(A);++count;}if(str.find(B) != string::npos)return count;str.append(A);++count;if(str.find(B) != string::npos)return count;return -1;}
};