[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 了,就返 ...
随机推荐
- linux的后台运行相关命令
screen -S name 创建一个名为name的后台,或者说bash面板,在这上面运行的任务不会因为连接断开而退出,且保留bash上的信息 screen -ls 列出所有的screen scree ...
- C# List<T>排序总结
这里有很多种方法对List进行排序,本文总结了三种方法,但有多种实现. 1.对基础类型排序 方法一: 调用sort方法,如果需要降序,进行反转: List<int> list = new ...
- Oracle两表关联,只取B表的第一条记录
背景: A表.B表两表关联,关联出来的结果里B表有不止一条,需求是只要B表结果中的某一条(按某字段排序) 首先想到了直接写个带排序的子查询去匹配外围的值,从这个结果集中只要第一条,但是经过验证发现, ...
- Java 15周作业
题目1:编写一个应用程序,输入用户名和密码,访问test数据库中t_login表(字段包括id.username.password),验证登录是否成功. 题目2:在上一题基础上,当登录成功后,将t_u ...
- JAVA添加WORD文档批注
本文将介绍在Java程序中如何给Word文档中的指定字符串添加批注.前文中,主要介绍的是针对某个段落来添加批注,以及回复.编辑.删除批注的方法,如果需要针对特定关键词或指定字符串来设置批注,可以参考本 ...
- django-用户浏览记录添加及商品详情页
视图函数views.py # /goods/商品id class DetailView(View): '''详情页''' def get(self, request, goods_id): '''显示 ...
- Codeforces Round #605 (Div. 3) B. Snow Walking Robot(构造)
链接: https://codeforces.com/contest/1272/problem/B 题意: Recently you have bought a snow walking robot ...
- 输入一个正整数n,生成一张2的乘方表,输出2*0—2*n的值。
#include<stdio.h>#include<math.h> //程序中调用幂函数pow(),需包含头文件math.h//void main(){ int i,n; pr ...
- PE安装器说明by双心
PE安装器说明by双心http://www.cnblogs.com/liuzhaoyzz/p/4204262.htmlhttps://share.weiyun.com/5749g5p基于omnifs3 ...
- webapp接口安全设计思路
在做webqq或者说app开发的时候,免不了会有接口是有权限的(如查询用户敏感信息等),这时接口安全设计思路就非常重要了. 简单一点,在APP中保存登录数据,每次调用接口时传输 程序员总能给自己找到偷 ...