• 686. 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").

    给定两个字符串A和B,找到A必须重复的最小次数,使得B是它的一个子字符串。如果没有这样的解决方案,返回-1。

    例如,用A =“abcd”和B =“cdabcdab”。返回3,因为通过重复三次(“abcdabcdabcd”),B是它的一个子串; 而B不是重复两次的子串(“abcdabcd”)。

    (1)思想1:因为要使得A包含B,所以当A的长度小于B的时候,就不断的叠加重复,直到A的长度大于等于B,并且计数。此时用find来查找,找见返回con,否则,再进行一次的复制,复制之后同样判断是否包含,包含则返回con+1;否则,未找到返回-1。

    C++代码:

     1 class Solution {
     2 public:
     3     int repeatedStringMatch(string A, string B) {
     4         int len_A=A.size(),len_B=B.size();
     5         string t=A;
     6         int con=1;
     7         while(t.size()<len_B)
     8         {
     9             t=t+A;
    10             con++;
    11         }
    12         if(t.find(B)!=string::npos)
    13             return con;
    14         t=t+A;
    15         if(t.find(B)!=string::npos)
    16             return con+1;
    17         else
    18             return -1;
    19         
    20     }
    21 };

    python代码:

     1 class Solution:
     2     def repeatedStringMatch(self, A, B):
     3         t=A
     4         con=1
     5         while len(t)<len(B):
     6             t=t+A
     7             con=con+1
     8         if t.find(B) != -1:
     9             return con
    10         t=t+A
    11         if t.find(B) != -1:
    12             return con+1
    13         else:
    14             return -1
  • 相关阅读:
    tbody的有趣问题
    如何去掉a标签的虚框
    在ubuntu下安装ruby on rails环境
    odoo 新建模块命令
    安装sentry的几个命令,日志监控系统
    腾讯云docker加速
    odoo技术笔记
    零基础实现摄像头的全平台直播 (一)内网直播的实现
    EasyNVR、EasyDSS二次开发RTMP、HLS流在web页面进行无插件播放(demo)
    EasyDSS流媒体服务器和EasyDSS云平台异同
  • 原文地址:https://www.cnblogs.com/sword-/p/8030024.html
Copyright © 2020-2023  润新知