Repeated String Match
💻 coding

Repeated String Match

1 min read 160 words
1 min read
ShareWhatsAppPost on X
  • 1To find the minimum repetitions of string A for B to be a substring, calculate the ceiling of B's length divided by A's length.
  • 2The solution involves constructing a new string by repeating A and checking if B is a substring of it.
  • 3If B is not found after the necessary repetitions, return -1 to indicate no solution exists.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To find the minimum repetitions of string A for B to be a substring, calculate the ceiling of B's length divided by A's length."

Repeated String Match

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.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class RepeatedStringMatchSoln
 {
 public int RepeatedStringMatch(string A, string B)
 {
 double len1 = A.Length;
 double len2 = B.Length;
 double times = Math.Ceiling(len2 / len1);
 var str = new StringBuilder();
 for (int i = 0; i < times; i++)
 {
 str.Append(A);
 }
 if (str.ToString().Contains(B))
 {
 return (int)times;
 }
 else
 {
 str.Append(A);
 if (str.ToString().Contains(B))
 return (int)times + 1; 
 }

 return -1;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 10 May 2020 · 1 min read · 160 words

Part of AskGif Blog · coding

You might also like