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 }
  • 相关阅读:
    BERT基础知识
    TorchText使用教程
    Pytorch-中文文本分类
    预处理算法_5_数据集划分
    预处理算法_4_表堆叠
    预处理算法_3_新增序列
    预处理算法_2_类型转换
    预处理算法_1_表连接
    爬取网站所有目录文件
    如何将Docker升级到最新版本
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11677965.html
Copyright © 2011-2022 走看看