LeetCode 686. Repeated String Match

Copyright: code word is not easy, please indicate the source: https://blog.csdn.net/qq_24309981/article/details/90263593

Description 1

Description

  • 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.

Example

  • input: A = “abcd” and B = “cdabcdab”.
  • output: 3
  • Explain:
    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.

2 code

#include <iostream>
#include <string>
using namespace std;

int repeatedStringMatch(string A, string B) {
	int res = -1;
	int N = B.size() / A.size() - (!(B.size() % A.size()));
	string temp = "";
	for (int i = 0; i < N; i++)
	{
		temp += A;
	}
	for (int i = 1; i < 3; i++)
	{
		temp += A;
		if (temp.find(B) != string::npos)
		{
			res = N + i;
			break;
		}
	}
	return res;
}

int main()
{
	string A = "abcd";
	string B = "cdabcdab";
	int res = repeatedStringMatch(A, B);
	cout << res << endl;
	system("pause");
    return 0;
}

3 explained

Repeating A, C give the string

  • Only when the length C of greater than or equal time B, B only possible substrings of C;
  • C is the maximum length (the length of the length A + B), the length C of unlimited increase is meaningless.

Guess you like

Origin blog.csdn.net/qq_24309981/article/details/90263593