686. Repeated String Match
Medium
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 <= 1041 <= b.length <= 104aandbconsist of lower-case English letters.
1 2 3 4 5 6 7 8 | class Solution { public int repeatedStringMatch(String a, String b) { String as = a; for (int rep = 1; rep <= b.length() / a.length() + 2; rep++, as += a) if (as.indexOf(b) != -1) return rep; return -1; } } |
1 2 3 4 5 6 7 8 9 10 11 12 | public int repeatedStringMatch(String A, String B) { int count = 0; StringBuilder sb = new StringBuilder(); while (sb.length() < B.length()) { sb.append(A); count++; } if(sb.toString().contains(B)) return count; if(sb.append(A).toString().contains(B)) return ++count; return -1; } |
No comments:
Post a Comment