LeetCode算法题-Repeated String Match(Java实现)

2021.12.22LeetCode每日一题——重复叠加字符串匹配 目录 重复叠加字符串匹配 描述 示例 1 示例 2 示例 3 示例 4 提示 方法一:暴力 方法二:Rabin-Karp 算法 方法三:KMP算法 重复叠加字符串匹配 描述 给定两个字符串a 和 b,寻找重复叠加字符串 a 的最小次数,使得字符串 b 成为叠加后的字符串 a 的子串,如果不存在则返回 -1。 注意:字符串 "abc"重复叠加 0 次是 "",重复叠加 1 次是"abc",重复叠加 2 次是"abcabc"。 示例 1 输入:a = "abcd"... 阅读详情

这是悦乐书的第289次更新,第307篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第156题(顺位题号是686)。给定两个字符串A和B,找到A必须重复的最小次数,使得B是它的子字符串。 如果没有这样的解决方案,返回-1。例如:

输入:A =“abcd”,B =“cdabcdab”。
输出:3
说明:因为重复A三次(“abcdabcdabcd”),B是它的子串; 和B不是A重复两次的子串(“abcdabcd”)。

注意:A和B的长度在1到10000之间。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

特殊情况:如果B的长度为0,直接返回0。

正常情况:使用循环,依次累加A,然后判断在累加后的字符串中是否存在字符串B,借助indexOf方法实现,同时统计累加的次数,如果能够找到,就返回最后的次数。但是有一种情况需要考虑,如果B根本就不是由A多次累加组成,那么循环就容易变成死循环,所以,在循环外面我们取得A和B的长度之商,如果count比商要大2,就直接返回-1。

public int repeatedStringMatch(String A, String B) {
    if (B.length() == 0) {
        return 0;
    }
    int len = B.length()/A.length();
    int count = 1;
    String C = A;
    while (C.indexOf(B) < 0) {
        C += A;
        count++;
        if (count-len > 2) {
            return -1;
        }
    }
    return count;
}

03 第二种解法

在第一种解法的基础上,我们还可以再优化下。依旧使用循环,只要A的长度小于B的长度,就累加一次A,并记数,然后开始判断累加后的A与B是否存在B是A的子串的关系。如果在A中能够直接找到B,就返回count;如果需要再累加一次A才能找到B,那么就返回count加1;如果前面两种情况都不符合,就返回-1。

public int repeatedStringMatch(String A, String B) {
    int count = 1;
    StringBuilder sb = new StringBuilder(A);
    while (sb.length() < B.length()) {
        sb.append(A);
        count++;
    }
    if (sb.indexOf(B) >= 0) {
        return count;
    }
    if (sb.append(A).indexOf(B) >= 0) {
        return count+1;
    }
    return -1;
}

04 小结

算法专题目前已日更超过四个月,算法题文章157+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

【数据挖掘】遗传算法原理浅析:什么是遗传算法?遗传算法的工作原理是什么? 遗传算法(Genetic Algorithm,GA),是进化算法的框架和核心。 各种进化算法有什么异同? - 及时物语的回答 - 知乎 https://www.zhihu.com/question/39152390/answer/901070749 阅读详情

相关推荐

SPAD 单光子雪崩二极管

SPAD,全称为,是一种高灵敏度的光电探测器件,能够在非常低的光照水平下检测单个光子。SPAD在工作时,当一个光子被探测器吸收后,能够触发一个雪崩效应,产生一个可以被检测到的电信号。

qq_42786033的博客 1万+

LeetCode#686: Repeated String Match

Description 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 = “cda...

水木今山的博客 388

libcrypto.so.10(OPENSSL_1.0.2)(64bit) is needed by erlang-22.0.7-1.el7.x86_64

今天安装Rabbitmq的 erlang-22.0.7-1.el7.x86_64.rpmrpm包时遇到了这个坑,害找到说是不容易;错误信息在下面; [root@iz2zef7u84js1qeeq00ewwz RabbitMQ]# rpm -ivh erlang-22.0.7-1.el7.x86_64.rpm warning: erlang-22.0.7-1.el7.x86_64.rpm: Header V4 RSA/SHA1 Signature, key ID 6026dfca: NOKEY error:

qq_45782349的博客 5783

Leetcode-686. Repeated String Match(string)

题目链接:点击打开链接 题目大意:给你两个字符串A和B,求A要最少重复几次才能让B成为它的子串。(这里有个坑,就是A本身已经包含了1次) 解题思路:用C++的string就好 解题代码: class Solution { public: int repeatedStringMatch(string A, string B) { string ss=A;

猴子姑娘呀的博客 1938

C#上位机实战:借助NetToPLCSim与西门子S7-1200仿真通信全攻略

本文详细介绍了如何使用C#开发上位机程序,通过NetToPLCSim与西门子S7-1200进行仿真通信的全过程。从环境准备、PLC仿真环境搭建、网络配置到C#代码实现,提供了完整的实战指南和常见问题解决方案,帮助开发者快速掌握工业自动化通信技术。

weixin_30596343的博客 441

从零搭建 AI 运维 Agent:告警自动诊断 + 修复的完整技术方案

适合读者:管理 5-50 台服务器的运维/SRE 工程师、技术负责人 技术栈:FastAPI + React + PostgreSQL + Redis + DeepSeek 关键词:AI运维、AIOps、自动化运维、智能告警、告警修复、Runbook自动化、DevOps、SRE、DeepSeek运维

weixin_38359457的博客 1640

string match java_LeetCode算法题-Repeated String Match(Java实现)

这是悦乐书的第289次更新,第307篇原创01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第156题(顺位题号是686)。给定两个字符串A和B,找到A必须重复的最小次数,使得B是它的子字符串。 如果没有这样的解决方案,返回-1。例如:输入:A =“abcd”,B =“cdabcdab”。输出:3说明:因为重复A三次(“abcdabcdabcd”),B是它的子串; 和B不是A重复两...

weixin_31190113的博客 186

STM32外部中断与事件机制深度解析:从硬件触发到软件响应

本文深入解析STM32外部中断与事件机制,从硬件触发到软件响应的完整流程。通过对比中断和事件的应用场景、响应速度及配置方法,帮助开发者优化嵌入式系统设计,特别适合需要低功耗或高实时性的项目。

weixin_29175469的博客 411

Leetcode——686. Repeated String Match

题目原址 https://leetcode.com/problems/repeated-string-match/description/ 题目描述 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...

想当厨子的程序媛 258

【系统架构设计师-2025上半年真题】综合知识-参考答案及详解(75题完全回忆版)

【系统架构设计师-2025上半年真题】案例分析-参考答案及部分详解

数据知道的博客 1万+

【KingSCADA】如何创建新应用

KingSCADA3.8集成开发环境是基于工程的应用管理模式,实现了对多个应用的集中开发和管理的功能,一个工程可以同时管理多个应用,即在KingSCADA3.8工程设计器中可以同时对多个应用进行开发,应用之间可以实现相互复制、粘贴等功能,大大提高了开发效率。(此处感觉和VS类似)使用KingSCADA3.8开发的系统称为应用,一个完整的应用一般包含以下部分或全部内容:IO设备、IO采集点、图形界面、动画链接、趋势曲线、报警和事件、历史记录、数据库、Web Server等部分。

做有价值的事,积累有价值的笔记! 3110

686. Repeated String Match*

686. Repeated String Match* https://leetcode.com/problems/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....

珍妮的选择的博客 307

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

leetcode 686 Repeated String Match

class Solution { public int repeatedStringMatch(String A, String B) { int count = 0; StringBuilder sb = new StringBuilder(); while (sb.length() < B.length()) { sb.append(A);

MRxjh的博客 461

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【Leetcode】686. Repeated String Match

686. Repeated String Match Easy 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 =...

蒋志碧的博客 200

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Leetcode挑战题——Repeated String Match

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 = "

森森 366

leetcode 686. Repeated String Match 题解

leetcode 686. Repeated String Match 题解。

Frank Chan的窝 875

LeetCode-Repeated String Match

LeetCode Java Repeated String Match

坟头草一米七五 199

LeetCode Repeated String Match

原题链接在这里:https://leetcode.com/problems/repeated-string-match/description/ 题目: 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 ...

weixin_30840573的博客 111

leetcode (Repeated String Match)

Title:Repeated String Match   686 Difficulty:Easy 原题leetcode地址: https://leetcode.com/problems/repeated-string-match/   1.    见代码注释 时间复杂度:O(n),一层一次for循环。 空间复杂度:O(1),没有申请额外空间。 /** * 首先A...

hsx1612727380的专栏 223

leetcode_686.Repeated String Match ? 待解决

Repeated String MatchGiven 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

wjheha的博客 460

LeetCode 686. 重复叠加字符串匹配(Repeated String Match)

686. 重复叠加字符串匹配 686. Repeated String Match 题目描述 给定两个字符串 A 和 B,寻找重复叠加字符串 A 的最小次数,使得字符串 B 成为叠加后的字符串 A 的子串,如果不存在则返回 -1。 举个例子,A = "abcd",B = "cdabcdab"。 答案为 3,因为 A 重复叠加三遍后为 "abcdabcdabcd",此时 B 是其子串;A 重复叠加两...

weixin_30455067的博客 147

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 substring of it. If no such solution, return -1. For example, with A = "abcd" and B = "cdabcdab". Re...

渣渣 519

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". Retur...

vir_lee的博客 352
上一篇: LeetCode算法题-Baseball Game(Java实现)
下一篇: LeetCode算法题-Longest Univalue Path(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值