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.

给2个字符串,找到字符串A需要重复的次数,使得字符串B是字符串A的子串,如果没有答案,则返回-1。

解法1:  Brute fore. a modified version of string find, which does not stop at the end of A, but continue matching by looping through A

解法2: KMP, O(n + m) version that uses a prefix table (KMP)

解法3: Rabin-Karp Algorithm

Java: 1

class Solution {
public int repeatedStringMatch(String A, String B) {
StringBuilder sb = new StringBuilder();
sb.append(A);
int count = 1;
while(sb.indexOf(B)<0){
if(sb.length()-A.length()>B.length()){
return -1;
}
sb.append(A);
count++;
} return count;
}  

Python: 1

class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
sa, sb = len(A), len(B)
x = 1
while (x - 1) * sa <= 2 * max(sa, sb):
if B in A * x: return x
x += 1
return -1 

Python: 3

# Time:  O(n + m)
# Space: O(1) class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
def check(index):
return all(A[(i+index) % len(A)] == c
for i, c in enumerate(B)) M, p = 10**9+7, 113
p_inv = pow(p, M-2, M)
q = (len(B)+len(A)-1) // len(A) b_hash, power = 0, 1
for c in B:
b_hash += power * ord(c)
b_hash %= M
power = (power*p) % M a_hash, power = 0, 1
for i in xrange(len(B)):
a_hash += power * ord(A[i%len(A)])
a_hash %= M
power = (power*p) % M if a_hash == b_hash and check(0): return q power = (power*p_inv) % M
for i in xrange(len(B), (q+1)*len(A)):
a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv
a_hash += power * ord(A[i%len(A)])
a_hash %= M
if a_hash == b_hash and check(i-len(B)+1):
return q if i < q*len(A) else q+1 return -1  

C++: 1

int repeatedStringMatch(string A, string B) {
for (auto i = 0, j = 0; i < A.size(); ++i) {
for (j = 0; j < B.size() && A[(i + j) % A.size()] == B[j]; ++j);
if (j == B.size()) return (i + j) / A.size() + ((i + j) % A.size() != 0 ? 1 : 0);
}
return -1;
}

C++: 2

int repeatedStringMatch(string a, string b) {
vector<int> prefTable(b.size() + 1); // 1-based to avoid extra checks.
for (auto sp = 1, pp = 0; sp < b.size(); ) {
if (b[pp] == b[sp]) prefTable[++sp] = ++pp;
else if (pp == 0) prefTable[++sp] = pp;
else pp = prefTable[pp];
}
for (auto i = 0, j = 0; i < a.size(); i += max(1, j - prefTable[j]), j = prefTable[j]) {
while (j < b.size() && a[(i + j) % a.size()] == b[j]) ++j;
if (j == b.size()) return (i + j) / a.size() + ((i + j) % a.size() != 0 ? 1 : 0);
}
return -1;
}

C++:

class Solution {
public:
int repeatedStringMatch(string A, string B) {
string t = A;
for (int i = 1; i <= B.size() / A.size() + 2; ++i) {
if (t.find(B) != string::npos) return i;
t += A;
}
return -1;
}
};

C++:

class Solution {
public:
int repeatedStringMatch(string A, string B) {
int m = A.size(), n = B.size();
for (int i = 0; i < m; ++i) {
int j = 0;
while (j < n && A[(i + j) % m] == B[j]) ++j;
if (j == n) return (i + j - 1) / m + 1;
}
return -1;
}
};

  

类似题目:  

[LeetCode] 459. Repeated Substring Pattern 重复子字符串模式

  

All LeetCode Questions List 题目汇总

[LeetCode] 686. Repeated String Match 重复字符串匹配的更多相关文章

  1. [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 su ...

  2. Leetcode 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 su ...

  3. 【LeetCode】686. Repeated String Match 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  4. 【Leetcode_easy】686. Repeated String Match

    problem 686. Repeated String Match solution1: 使用string类的find函数: class Solution { public: int repeate ...

  5. Leetcode686.Repeated String Match重复叠加字符串匹配

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

  6. 686. Repeated String Match 字符串重复后的子字符串查找

    [抄题]: Given two strings A and B, find the minimum number of times A has to be repeated such that B i ...

  7. 686. Repeated String Match判断字符串重复几次可以包含另外一个

    public static int repeatedStringMatch(String A, String B) { //判断字符串a重复几次可以包含另外一个字符串b,就是不断叠加字符串a直到长度大 ...

  8. 686. Repeated String Match

    方法一.算是暴力解法吧,拼一段找一下 static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); cl ...

  9. 【刷题笔记】686. Repeated String Match

    题意 题目大意是,给两个字符串 A 和 B,问 B 是否能成为 A+A+A+...+A 的子字符串,如果能的话,那么最少需要多少个 A? 暴力解法 直接 A+A+...,到哪次 A 包含 B 了,就返 ...

随机推荐

  1. 使用flask搭建微信公众号:实现签到功能

    终于到了实战阶段.用微信公众号实现一个简单的签到功能. 前情提要: 微信公众号token验证失败 使用flask搭建微信公众号:完成token的验证 使用flask搭建微信公众号:接收与回复消息 程序 ...

  2. CentOS 6.x 无法格式化大于16TB的ext4分区处理

    CentOS 6.x 在格式化大于16TB的ext4分区时,会提示如下错误: mke2fs 1.41.12 (17-May-2010) mkfs.ext4: Size of device /dev/s ...

  3. [后端]gitlab之gitlab-ci自动部署

    转发:https://www.jianshu.com/p/df433633816b 简介 gitlab-ci全称是gitlab continuous integration的意思,也就是持续集成.中心 ...

  4. nginx 添加用户认证

    nginx 添加用户认证  nginx 配置文件添加: 配置代理添加用户认证:server {   listen       ;   server_name localhost;   location ...

  5. 开源项目 08 IOC Autofac

    using Autofac; using System; using System.Collections.Generic; using System.Linq; using System.Text; ...

  6. 洛谷P2744 量取牛奶

    题目 DP或者迭代加深搜索,比较考验递归的搜索. 题目第一问可以用迭代加深搜索限制层数. 第二问需要满足字典序最小,所以我们可以在搜索的时候把比当前答案字典序大的情况剪枝掉. 然后考虑怎么搜索,对于每 ...

  7. ES6 解构对象和数组

    1.解构对象 let saveFiled = { extension: "jpg", name:"girl", size:14040 }; ES5 functi ...

  8. mysql .字符串转日期

    insert into share (uid, mapId, isdir, type, pwd, shareTime, overTime, price) values (1, 10, 0, 1,&qu ...

  9. element ui 怎么去修改el-date-picker的时间

    <el-date-picker v-model="formSearch.timeRange" type="daterange" placeholder=& ...

  10. mysql 为啥用b+ 树

    原因就是为了减少磁盘io次数,因为b+树所有最终的子节点都能在叶子节点里找见, 所以非叶子节点只需要存`索引范围和指向下一级索引(或者叶子节点)的地址` 就行了, 不需要存整行的数据,所以占用空间非常 ...