LeetCode 686: Repeated String Match Solution
Master LeetCode problem 686 (Repeated String Match), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
686. Repeated String Match
Problem Explanation
Explanation
To solve this problem, we need to determine the minimum number of times we should repeat string a in order to make it long enough so that string b becomes a substring of it. We can achieve this by repeatedly concatenating a and checking if b is a substring of the concatenated string. We can optimize this process by calculating the maximum number of repetitions needed based on the lengths of strings a and b.
- Calculate the maximum number of repetitions needed:
repeat = ceil(b.length() / a.length()). - Generate a string by concatenating
arepeattimes. - Check if
bis a substring of the generated string. If it is, returnrepeat. If not, check one more repetition and return-1ifbis still not a substring.
The time complexity of this approach is O(n * m) where n is the length of string a and m is the length of string b.
Solution Code
class Solution {
public int repeatedStringMatch(String a, String b) {
int repeat = (int) Math.ceil((double)b.length() / a.length());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < repeat; i++) {
sb.append(a);
}
if (sb.toString().contains(b)) {
return repeat;
}
sb.append(a);
if (sb.toString().contains(b)) {
return repeat + 1;
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 686 (Repeated String Match)?
This page provides optimized solutions for LeetCode problem 686 (Repeated String Match) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 686 (Repeated String Match)?
The time complexity for LeetCode 686 (Repeated String Match) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 686 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 686 in Java, C++, or Python.