• Leetcode: 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.
    
    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").
    
    Note:
    The length of A and B will be between 1 and 10000.

    The idea is to keep string builder and appending until the length A is greater or equal to B.

    use a while loop to keep adding A to stringBuilder until sb.length() >= B.length(); see if B is a substring of sb.

    why == should break as well?  because it's possible for sb == B. like A = "ABC", B = "ABCABC"

     1 class Solution {
     2     public int repeatedStringMatch(String A, String B) {
     3         StringBuilder sb = new StringBuilder();
     4         int res = 0;
     5         while (sb.length() < B.length()) {
     6             sb.append(A);
     7             res ++;
     8         }
     9         if (sb.toString().contains(B)) return res;
    10         if (sb.append(A).toString().contains(B)) return ++res;
    11         return -1;
    12     }
    13 }
  • 相关阅读:
    异常处理、网络编程
    内置函数、反射、__str__、__del__、元类
    tomcat 拒绝服务
    html标签
    google 与服务器搭建
    liunx centox ssh 配置
    java 泛型
    Windows Mysql安装
    java 空对象
    java 动态代理(类型信息)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11677965.html
Copyright © 2020-2023  润新知