686. Repeated String Match
https://leetcode.com/problems/repeated-string-match/
Given two strings a
and b
, return the minimum number of times you should repeat string a
so that string b
is a substring of it. If it is impossible for b
to be a substring of a
after repeating it, return -1
.
Notice: string "abc"
repeated 0 times is ""
, repeated 1 time is "abc"
and repeated 2 times is "abcabc"
.
Example 1:
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
Example 2:
Input: a = "a", b = "aa"
Output: 2
Example 3:
Input: a = "a", b = "a"
Output: 1
Example 4:
Input: a = "abc", b = "wxyz"
Output: -1
Constraints:
1 <= a.length <= 104
1 <= b.length <= 104
a
andb
consist of lower-case English letters.
Solution
class Solution {
public int repeatedStringMatch(String a, String b) {
StringBuilder sb = new StringBuilder();
int count=0;
while(sb.length()<=b.length()){
count++;
sb.append(a);
}
if(sb.indexOf(b) != -1) return count;
sb.append(a);
if(sb.indexOf(b) != -1) return count+1;
return -1;
}
}
public int repeatedStringMatch(String A, String B) {
int i = 0;
int j = 0;
int result = 0;
int k = 0;
while (j < B.length()) {
if (A.charAt(i) == B.charAt(j)) {
i++;
j++;
if (i == A.length()) {
i = 0;
result++;
}
} else {
k++;
if (k == A.length()) {
return -1;
}
i = k;
j = 0;
result = 0;
}
}
if (i > 0) {
result++;
}
return result;
}
Last updated
Was this helpful?