您的位置:首页 > 其它

Repeated String Match问题及解法

2017-10-13 12:18 363 查看
问题描述:

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.
问题分析:

我们分析可知,B的长度很大程度上决定了A要重复几次,我们确定好A重复的次数范围后,在重复后的字串中查找B是否存在,若存在,重复次数最小的那个值即为答案。

过程详见代码:

int num = B.length() / A.length();
if (!num) num = 1;
string str = A;

for (int i = 1; i < num; i++) str += A;
for (int i = 0; i < 2; i++)
{
if (str.find(B) != string::npos) return num + i;
str += A;
}
return -1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: