问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3963 访问。

给定两个字符串 A 和 B, 寻找重复叠加字符串A的最小次数,使得字符串B成为叠加后的字符串A的子串,如果不存在则返回 -1。

举个例子,A = "abcd",B = "cdabcdab"。

答案为 3, 因为 A 重复叠加三遍后为 “abcdabcdabcd”,此时 B 是其子串;A 重复叠加两遍后为"abcdabcd",B 并不是其子串。

注意:A 与 B 字符串的长度在1和10000区间范围内。


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.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3963 访问。

public class Program {

    public static void Main(string[] args) {
var A = "abcd";
var B = "cdabcdab"; var res = RepeatedStringMatch(A, B);
Console.WriteLine(res); Console.ReadKey();
} private static int RepeatedStringMatch(string A, string B) {
var length = Math.Ceiling(B.Length / (double)A.Length) + 1;
var repeat = new StringBuilder();
for(var i = 0; i < length; i++) {
repeat.Append(A);
if(repeat.Length < B.Length) continue;
if(repeat.ToString().Contains(B)) return i + 1;
}
return -1;
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3963 访问。

3

分析:

设字符串A的长度是 m,字符串B的长度是 n,由于部分运行库的使用,以上算法的时间复杂度应当为:  。

最新文章

  1. VPS拨号主机自动拨号脚本(centos7)
  2. java课后作业
  3. yii 事物
  4. React入门资源整理
  5. Java 中的resultset详解
  6. php __autoload使用
  7. redis的持久化 rdb和aof
  8. 在SrollView中嵌套GridView或ListView(转)
  9. JPA Advanced Mappings(映射)
  10. assert断言检测
  11. onselectstart属性解决双击出现的蓝色区域
  12. Windows &amp; RabbitMQ:Shovel
  13. YSLOW(一款实用的网站性能检测工具)
  14. Solidity的三种转账方式与比较
  15. 从PHP官方镜像创建开发镜像
  16. VMware Authorization Service不能启动 VMware虚拟机状态已挂起无法恢复解决方案
  17. 【C语言】 8421BCD码与二进制的转换
  18. FFT自看
  19. js精准时间迭代器(定时器)
  20. open /etc/docker/certs.d/registry.access.redhat.com/redhat-ca.crt: no such file or directory 解决方案

热门文章

  1. 三种安装python第三方库的方法
  2. C#中的类与对象
  3. 【week1错题集】
  4. 设计模式:template method模式
  5. AI面试题之深入浅出卷积网络的平移不变性
  6. Python语言及其应用|PDF高清完整版免费下载|百度云盘|Python
  7. http安全
  8. 聊聊Django应用的部署和性能的那些事儿
  9. 网络通信协议、UDP通信、TCP通信
  10. centos7安装部署docker