share my java solution!


  • 7
    T
    class Solution {
        public int repeatedStringMatch(String A, String B) {
            StringBuilder sb = new StringBuilder();
            sb.append(A);
            int count = 1;
            while(sb.indexOf(B)<0){
                if(sb.length()-A.length()>B.length()){
                    return -1;
                }
                sb.append(A);
                count++;
            }
            
            return count;
    }
    

  • 0
    W
    if(sb.length()-A.length()>B.length()){
       return -1;
    }
    

    seems obvious when I wrote down two strings A and B.But could you please describe why you use it as a if statement, what situation are you trying to show that B could never be s substring of A no matter how many times we append StringBuilder.


  • 3
    S

    @w1024020103 If the string obtained as concatenating copies of string A has a length greater than the sum of the lengths of A and B and still it does not have B as a substring, then any further A-concatenation is useless.


  • 1
    T

    @tiandiao123 I have a quite similar solution

    class Solution {
        public int repeatedStringMatch(String A, String B) {
            StringBuilder sb = new StringBuilder();
            sb.append(A);
            int count = 1;
            while(sb.indexOf(B)<0){
                sb.append(A);
                if(sb.length()>B.length() && sb.indexOf(B)<0){
                    return -1;
                }
                ++count;
                
            }
            
            return count;
        }
    }
    

  • 1

    @Toaster A="abc",B="cabca" is wrong


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.