当前位置:网站首页>[LeetCode每日一题] |686.重复叠加字符串匹配
[LeetCode每日一题] |686.重复叠加字符串匹配
2022-06-11 15:50:00 【AI应用算法工程师(AI+安全)】
题目链接
https://leetcode-cn.com/problems/repeated-string-match
题目描述
题目难度:中等
给定两个字符串 a和 b,寻找重复叠加字符串 a的最小次数,使得字符串 b成为叠加后的字符串 a的子串,如果不存在则返回 -1。
注意:字符串 "abc" 重复叠加 0 次是 "",重复叠加 1 次是 "abc",重复叠加 2 次是 "abcabc"。
解题思路
Python里字符串匹配是很容易的,直接调用 x.find(y)即可找到 y在 x中的位置。
但本题中需要把 a重复叠加若干遍后,才 有可能 包含子串 b(也可能永远都不包含),因此不能无限的堆叠 a,而是要找到一个合理的上界 k ,使得 如果 a重复叠加 k 次后 b仍不是其子串,则无论叠加多少次, b永远不会是其子串。
因此这里的核心就是确定这个上界 k,此处应该有一个GIF图,就很好理解了,但由于GIF制作有(不)些(会)麻(制)烦(做),因此直接给出结论:
可以使 len(a) * k >= len(a) + len(b)成立的 k 都是可行的。
所以只要重复堆叠 a,直到其长度大于 len(a) + len(b),然后调用.find()即可找到 b在堆叠字符串中的位置,通过这个位置可以判断最少堆叠多少次后可以包含 b。
# Python3
class Solution:
def repeatedStringMatch(self, a: str, b: str) -> int:
res = len(b) // len(a) + 1
temp = ''
for _ in range(res):
temp += a
temp += a
# 提交后发现使用temp.find(b)方法需要耗时84ms,
# 而下面这种直接遍历只需要40ms,因此改用遍历
for i in range(len(temp) - len(b) + 1):
if b == temp[i: i + len(b)]:
x, y = divmod(i + len(b), len(a))
if y > 0:
x += 1
return x
return -1
return x
return -1
边栏推荐
- openGauss数据库闪回功能验证
- 收藏 | 可解释机器学习发展和常见方法!
- postgresql启动过程
- Graduation project wechat applet OUC campus navigation (I) topic selection and opening report
- 3000 words to teach you how to use mot
- 轻松上手使用gs_dump和gs_dumpall命令导出数据
- Performance of MOS transistor 25n120 of asemi in different application scenarios
- Ai4db: AI slow SQL root cause analysis
- 用户界面之工具栏详解-AutoRunner自动化测试工具
- Opengauss database flashback function verification
猜你喜欢

openGauss数据库JDBC环境连接配置(Eclipse)

Discussion on opengauss parallel decoding

Factory calibrated gravity: working principle and installation position of carbon monoxide sensor, calibration standard description

收藏 |彻底搞懂感受野的含义与计算

使用Cloud DB构建APP 快速入门-快游戏篇

Overview and example analysis of opengauss database performance tuning

openGauss 3.0.0版本正式发布,立即体验社区首个轻量版本

YEF 2022昨日开幕,多网络平台全程免费直播,开启在线技术盛宴!

Open the door of the hybrid cloud market, Lenovo xcloud's way to break the situation

Yiwenjiaohui your database system tuning
随机推荐
[Yugong series] June 2022 Net architecture class 079 cluster principle of distributed middleware schedulemaster
从内核代码了解SQL如何解析
[0006] titre, mots clés et description de la page
[golang] leetcode special training - array and slice
openGauss AI能力升级,打造全新的AI-Native数据库
AI function of cutting-edge technology exploration: slow SQL discovery
了解下openGauss的密态支持函数/存储过程
Opengauss database JDBC environment connection configuration (eclipse)
【愚公系列】2022年06月 .NET架构班 077-分布式中间件 ScheduleMaster加载程序集定时任务
网站上的 breadcrumb 使用场景浅析
PostgreSQL startup process
使用Cloud DB构建APP 快速入门-快游戏篇
DHCP协议实例化分析
Why are bugs changing more and more?
wget命令使用
三千字教你使用MOT
openGauss数据库性能调优概述及实例分析
Graduation project wechat applet OUC campus navigation (I) topic selection and opening report
Selenium-- display waiting (medium) -- detailed explanation
前沿科技探究之AI工具:Anomaly-detection