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
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;
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
Aand
Bwill
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;
相关文章推荐
- [LeetCode] Repeated String Match 重复字符串匹配
- LeetCode -- Google -- Interview Process. 1. Repeated String Match(java)
- Permutation in String问题及解法
- Reverse Vowels of a String问题及解法
- Oracle问题之literal does not match format string
- Reverse String II问题及解法
- Repeated String Match
- leetcode 686 Repeated String Match
- token 6.x-1.17 "preg_match_all() expects parameter 2 to be string, array given in token_scan()" 问题解决
- LeetCode Weekly Contest 52 Repeated String Match(string)
- Repeated DNA Sequences问题及解法
- Unique Substrings in Wraparound String问题及解法
- leetcode 686 Repeated String Match
- Leetcode挑战题——Repeated String Match
- Find All Anagrams in a String问题及解法
- String-686-Repeated String Match
- First Unique Character in a String问题及解法
- Reverse Words in a String问题及解法
- Rotate String 问题使用取余解法
- Number of Segments in a String问题及解法