zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    利用Telnet来模拟Http请求 有GET和POST两种
    WebConfig特殊字符的转义!
    userprofile同步用户失败的原因和解决方案
    linux mysql表名大小写
    web.py 中文模版报错
    docker 开启远程
    web.py 笔记
    python 安装influxdb-python
    安装pip
    influxdb 命令
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11677965.html
Copyright © 2011-2022 走看看