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. 逆向破解之160个CrackMe —— 008-009

    CrackMe —— 008 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...

  2. 运行pyqt4生成py文件增加代码

    if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWid ...

  3. Python开发笔记:网络数据抓取

    网络数据获取(爬取)分为两部分: 1.抓取(抓取网页) · urlib内建模块,特别是urlib.request · Requests第三方库(中小型网络爬虫的开发) · Scrapy框架(大型网络爬 ...

  4. django-签名加密模块It's dangerous--加密token

    https://juejin.im/entry/56b30250df0eea0054375e1d 安装 pip install itsdangerous 使用 from itsdangerous im ...

  5. 防火墙firewalld

    增加外部可访问的端口 启动: systemctl start firewalld 查看状态: systemctl status firewalld 停止: systemctl stop firewal ...

  6. Xshell6和Xftp6初步使用

    Xshell6和Xftp6初步使用 一.Xshell6和Xftp6介绍: Xshell6:可以在Windows界面下用来访问远端不同系统下的服务器,从而比较好的达到远程控制终端的目的. Xftp6:是 ...

  7. javascript使用history api防止|阻止页面后退

    奇葩需求啥时候都会有,最近有个需求是不允许浏览器回退,但是所有页面都是超链接跳转,于是乎脑壳没转弯就回答了做不到,结果尼玛被打脸了,这打脸的声音太响,终于静下心来看了下history api. 先上代 ...

  8. Kubernetes集群部署(yum部署)

    环境准备 Kubernetes-Master:192.168.37.134    #yum install kubernetes-master etcd flannel -y Kubernetes-n ...

  9. 用Visual Studio编写UDF的一点小技巧(二)

  10. 从0开始部署GPU集群-1:k8s部署生态

    1 k8s:nvidia deepops 2  批处理:华为volcano 3 工作流:argo