LeetCode 686. 重复叠加字符串匹配(Repeated String Match)
2024-08-31 13:43:34
686. 重复叠加字符串匹配
686. Repeated String Match
题目描述
给定两个字符串 A 和 B,寻找重复叠加字符串 A 的最小次数,使得字符串 B 成为叠加后的字符串 A 的子串,如果不存在则返回 -1。
举个例子,A = "abcd",B = "cdabcdab"。
答案为 3,因为 A 重复叠加三遍后为 "abcdabcdabcd",此时 B 是其子串;A 重复叠加两遍后为 "abcdabcd",B 并不是其子串。
注意:
A 与 B 字符串的长度在 1 和 10000 区间范围内。
LeetCode686. Repeated String Match
Java 实现
class Solution {
public int repeatedStringMatch(String A, String B) {
int m = A.length(), n = B.length();
StringBuilder str = new StringBuilder();
for (int i = 1; i <= n / m + 2; i++) {
str.append(A);
if (str.indexOf(B) != -1) {
return i;
}
}
return -1;
}
}
class Solution {
public int repeatedStringMatch(String A, String B) {
int count = 0;
StringBuilder str = new StringBuilder();
while (str.length() < B.length()) {
str.append(A);
count++;
}
if (str.toString().contains(B)) {
return count;
}
if (str.append(A).toString().contains(B)) {
return ++count;
}
return -1;
}
}
相似题目
参考资料
- https://leetcode.com/problems/repeated-string-match/
- https://leetcode-cn.com/problems/repeated-string-match/
最新文章
- c 小工具的使用
- MongoDB安全和认证
- css 修改滚动条
- typedef关键字
- 读书笔记——Windows环境下32位汇编语言程序设计(9)ANSII字符大小写转大写
- test generation和MBIST
- 剑指Offer:从第一个字符串中删除第二个字符串中出现过的所有字符
- Makefile学习与进阶之Makefile.am和$$(M)的意思
- Android KitKat 4.4 Wifi移植之Wifi driver
- UVA 1546 - Complete the sequence!(差分法)
- EF 关系描述
- jQuery扩展easyui.datagrid,添加数据loading遮罩效果代码
- VS中Ctrl+F5(开始执行不调试)一闪而过问题
- Netty4.x整合SpringBoot2.x使用Protobuf3详解
- django的闪现和增、删、改、查
- C# WebApi过滤器(开发接口必备利器)
- 050 sqoop的使用
- HashSet, HashTable
- Singer 学习十 同步模式
- H5做的商城客户端,效果很不错