168.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.
给定两个字符串A和B,找到A必须重复的最小次数,使得B是它的子字符串。 如果没有这样的解决方案,返回-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").
返回3,因为重复A三次(“abcdabcdabcd”),B是它的子串; 和B不是A重复两次的子串(“abcdabcd”)。
Note:
The length of A
and B
will be between 1 and 10000.
A和B的长度在1到10000之间。
解答:
1 class Solution { 2 public int repeatedStringMatch(String A, String B) { 3 int count=0; 4 StringBuilder sb=new StringBuilder(); 5 while(sb.length()<B.length()){ 6 sb.append(A); 7 count++; 8 } 9 if(sb.toString().contains(B)) return count; 10 else if(sb.append(A).toString().contains(B)) return ++count; 11 return -1; 12 } 13 }
详解: