[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 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 重复字符串匹配的更多相关文章
- [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 ...
- 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 ...
- 【LeetCode】686. Repeated String Match 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【Leetcode_easy】686. Repeated String Match
problem 686. Repeated String Match solution1: 使用string类的find函数: class Solution { public: int repeate ...
- Leetcode686.Repeated String Match重复叠加字符串匹配
给定两个字符串 A 和 B, 寻找重复叠加字符串A的最小次数,使得字符串B成为叠加后的字符串A的子串,如果不存在则返回 -1. 举个例子,A = "abcd",B = " ...
- 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 ...
- 686. Repeated String Match判断字符串重复几次可以包含另外一个
public static int repeatedStringMatch(String A, String B) { //判断字符串a重复几次可以包含另外一个字符串b,就是不断叠加字符串a直到长度大 ...
- 686. Repeated String Match
方法一.算是暴力解法吧,拼一段找一下 static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); cl ...
- 【刷题笔记】686. Repeated String Match
题意 题目大意是,给两个字符串 A 和 B,问 B 是否能成为 A+A+A+...+A 的子字符串,如果能的话,那么最少需要多少个 A? 暴力解法 直接 A+A+...,到哪次 A 包含 B 了,就返 ...
随机推荐
- Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.qingmu.seller.entity.OrderMaster
org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before ...
- Docker 部署 vue 项目
Docker 部署 vue 项目 Docker 作为轻量级虚拟化技术,拥有持续集成.版本控制.可移植性.隔离性和安全性等优势.本文使用Docker来部署一个vue的前端应用,并尽可能详尽的介绍了实现思 ...
- 最新NetMonitor代码
<Window x:Class="NetMonitor.MainWindow" xmlns="http://schemas.microsoft.com/winfx/ ...
- numpy函数库中一些常用函数的记录
##numpy函数库中一些常用函数的记录 最近才开始接触Python,python中为我们提供了大量的库,不太熟悉,因此在<机器学习实战>的学习中,对遇到的一些函数的用法进行记录. (1) ...
- node 日志 log4js 错误日志记录
SET DEBUG=mylog:* & npm start 原文出处:http://blog.fens.me/nodejs-log4js/ 1. 默认的控制台输出 我们使用express框架时 ...
- Kali Linux 2019.4 vmtool安装
1.如图点击 2.桌面上光盘把vmtool拿出来 然后解压加权限并执行 3.一路回车即可 如下图安装成功 然后reboot重启即可
- 【洛谷P4319】 变化的道路 线段树分治+LCT
最近学了一下线段树分治,感觉还蛮好用... 如果正常动态维护最大生成树的话用 LCT 就行,但是这里还有时间这一维的限制. 所以,我们就把每条边放到以时间为轴的线段树的节点上,然后写一个可撤销 LCT ...
- WinDbg常用命令系列---.cmdtree
.cmdtree 简介 使用形式 .cmdtree cmdfile 参数 cmdfile命令文件,包含多个你需要的命令.必须是一个文本档 使用步骤 1.使用命令创建文本文件test.wl,使用以下示例 ...
- Redis存储字符串
1.set和get实现字符串存取: 键的名字相同,会对以前的值进行覆盖: 2.++操作: 3.--操作: 4.加任意数值的数字: 5.减任意数值的数字: 6.拼接字符串: 7.删除:
- linux patch 简单学习
使用patch 我们可以方便的进行软件补丁包处理,以下演示一个简单的c 项目补丁处理 原代码 app.c #include <stdio.h> int main(){ printf(&qu ...