[LeetCode]541. Reverse String II(间隔反转字符串)

UCIE Specification详解(八) Logical Physical Layer(逻辑物理层) 阅读详情

541. Reverse String II

原题链接
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:

  • The string consists of lower English letters only.
  • Length of the given string and k will in the range [1, 10000]

题目大意:

  • 给定一个字符串和一个整数k,你需要反转从字符串开始计数的每2k个字符的前k个字符。
  • 如果剩余少于k个字符,则将剩余的所有字符都反转。
  • 如果小于2k但大于或等于k个字符,则反转前k个字符,并将另一个作为原始字符
  • 最重要的就是理解题意,刚开始题目没看懂很伤

代码如下:

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
    string reverseStr(string s, int k) {//9ms
        int sLength = s.length();  
        int business = sLength/(2*k);//商
        int remainder = sLength - business*k*2;//余数
        for(int i=0; i<business; i++){
            for(int m=0,sta=i*k*2; m<k/2; m++){//翻转每2K个字符的前K个字符
                char temp = s[sta];
                s[sta] = s[sta+ k-1 - m*2];
                s[sta+ k-1 - m*2] = temp;
                sta++;
            }
        }
        if(remainder<k){//剩余少于k个字符,将所有字符都反转 (剩余必定小于2k个字符)
            for(int m=0,sta=business*k*2; m<remainder/2; m++){
                char temp = s[sta];
                s[sta] = s[sta+ remainder-1 - m*2];
                s[sta+ remainder-1 - m*2] = temp;
                sta++;
            }
        }
        else{//小于2k但大于或等于k个字符,反转前k个字符
            for(int m=0,sta=business*k*2; m<k/2; m++){//翻转前K个字符
                char temp = s[sta];
                s[sta] = s[sta+ k-1 - m*2];
                s[sta+ k-1 - m*2] = temp;
                sta++;
            }
        }
        return s;
    }

};
int main()
{
    Solution a;
    string s;
    cin >> s;
    cout << "s = " << s << endl;
    cout << "翻转后s = " << a.reverseStr1(s, 4) << endl;
    return 0;
}

做完之后发现里面的三个for循环可以单独写一个方法出来,用来处理翻转字符串s第sta位置后的K个元素
改进后代码:

string reverseStr1(string s, int k) {//6ms
        int sLength = s.length();
        int business = sLength/(2*k);//商
        int remainder = sLength - business*k*2;//余数
        for(int i=0; i<business; i++){
            reverseK(s, i*k*2, k);//翻转每2K个字符的前K个字符
        }
        if(remainder<k){//剩余少于k个字符,将所有字符都反转 (剩余必定小于2k个字符)
            reverseK(s, business*k*2, remainder);
        }
        else{//小于2k但大于或等于k个字符,反转前k个字符
            reverseK(s, business*k*2, k);//翻转前K个字符
        }
        return s;
    }
    void reverseK(string &s, int sta, int k){//翻转字符串第sta位置后的K个元素
        for(int m=0; m<k/2; m++){
                char temp = s[sta];
                s[sta] = s[sta+ k-1 - m*2];
                s[sta+ k-1 - m*2] = temp;
                sta++;
        }
    }
【大模型学习】第二十四章 生成式人工智能(GAI)简介 ‌的AI技术,其核心目标是通过学习数据中的规律,生成与训练数据类似但全新的文本、图像、音频、视频甚至代码。生成式人工智能(GAI)是一类能够‌。 阅读详情

相关推荐

(实战)[re:Invent 2018]-001:赛道分析-(致敬1024)

打印log

Rainbow 2784

字符串2——反转字符串2

反转字符串

wtlll的博客 1686

信息流广告ROI线性预测看板&投放分析监控看板展示&数据处理入库全流程

此看板数据量太大,在tableau public部署运行速度极慢,因此用图片作展示 数据清洗

Larry_Westside的博客 2317

力扣(leetcode)第541题反转字符串II(Python)

给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。最后,我写了一篇MySQL教程,里面详细的介绍了MySQL的基本概念以及操作指令等内容,欢迎阅读!如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。如果剩余字符少于 k 个,则将剩余字符全部反转。输入:s = “abcdefg”, k = 2。输入:s = “abcd”, k = 2。输出:“bacdfeg”s 仅由小写英文组成。

qq_58737789的博客 848

VS2022+Qt6保姆级配置指南:从插件安装到项目互通全流程(附常见错误解决)

本文提供了一份详细的Visual Studio 2022与Qt6集成开发环境配置指南。从插件安装、环境搭建到项目创建与互通,涵盖了全流程操作步骤,并针对常见的配置错误和调试问题提供了实用的解决方案,帮助开发者高效构建企业级桌面应用。

nginx7reverse的博客 1208

app编写需要哪种语言

原生App开发:优选Swift(iOS)和Kotlin(Android)。跨平台App开发:优选Flutter(Dart)和React Native(JavaScript)。游戏App开发:优选Unity(C#)和Unreal Engine(C++)。低代码工具:适合简单、快速的App制作。

fanying_98的博客 2072

Leetcode-541:反转字符串 II

题目链接 https://leetcode-cn.com/problems/reverse-string-ii/ 题目 给定一个字符串 s 和一个整数 k,从字符串开头算起,每 2k 个字符反转前 k 个字符。 如果剩余字符少于 k 个,则将剩余字符全部反转。 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。 示例 示例 1: 输入:s = "abcdefg", k = 2 输出:"bacdfeg" 示例 2: 输入:s = "abcd", k =

道纪书生的博客 396

WordPress主题开发实战:从零开始手把手教你创建自定义主题(含常用函数大全)

本文是一份WordPress主题开发实战指南,从零开始手把手教你创建自定义主题。内容涵盖主题核心文件结构、模板层级与循环机制、函数与钩子的运用,并附有详细的常用函数大全,帮助开发者彻底掌握主题开发的核心技能,实现从使用者到创造者的转变。

weixin_27943395的博客 257

LeetCode题练习与总结:反转字符串 Ⅱ -- 541

本文详细介绍了如何通过将字符串转换为字符数组,并利用双指针技术反转特定字符区间,以解决给定字符串每2k个字符反转前k个字符的问题,同时分析了算法的时间复杂度和空间复杂度。

一直学习永不止步 1762

蓝牙6.0的‘新雷达’:Channel Sounding信道探测,真能比UWB更香吗?

本文探讨了蓝牙6.0的Channel Sounding信道探测技术在室内定位领域的应用潜力。通过与UWB技术的对比分析,揭示了其在成本、功耗和兼容性方面的优势,特别是在智能门锁、物品追踪等场景中的商业价值。Channel Sounding技术不仅具备亚米级精度,还能通过现有蓝牙设备实现零边际成本部署,为物联网应用提供了新的解决方案。

weixin_29288313的博客 334

不用公网IP!用Ollama+Chatbox搭建家庭AI助手(内网穿透方案对比)

本文详细介绍了如何利用Ollama和Chatbox在家庭局域网中搭建本地AI助手,无需公网IP即可实现内网穿透。通过对比不同穿透方案(如Tailscale、FRP等),提供最优配置建议,帮助用户低成本部署隐私安全的家庭AI系统,适用于智能家居、儿童教育等多种场景。

weixin_26765287的博客 468

leetcode541. 反转字符串 II

​分段处理:通过步进2k长度的循环,确保每次处理正确的区间。​边界处理:精确判断剩余字符数量,避免越界访问。​双指针法:高效实现区间内字符反转,时间复杂度最优。​适用性:适用于所有需要分段反转的场景,如日志处理、数据分块等。

m0_49844997的博客 531

从Overleaf上导出Latex论文发布到arxiv详细教程(常见问题与解决)

如果是做cv的论文请选择“Computer Vision and Pattern Recognition”,选择“Artificial Intelligence”可能会被on hold,貌似这个指的是传统的人工智能?我用公司邮箱注册发布一篇论文,一个多月还是“on hold”状态,换成edu邮箱第二天就被发布了。3、有可能是subject class选错了,编辑会帮你手动选择,然后发一封邮件告知你解除……报错缺失bbl等文件,这是因为从Menu中下载的话,是没有bbl文件的。论文被on hold。

沉迷单车的追风少年 3591

LeetCode //C - 541. Reverse String II

【代码】LeetCode //C - 541. Reverse String II。

Made in Code 2094

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

深度学习工具包 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 541.反转字符串 II(Reverse String II)

Leetcode 541.反转字符串 II 1 题目描述(Leetcode题目链接)   给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。 如果剩余字符少于 k 个,则将剩余字符全部反转。 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。 输入: s = "abcdefg", k = 2 输出: "bacdfeg" 提示: 该字符串只包含小写英文字母。 给定字符串的长度和 k 在 [1, 10000] 范围内

qq_39378221的博客 278

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

【String-easy】541. Reverse String II 反转的元素,有反转个数和间隔

1. 题目原址 https://leetcode.com/problems/reverse-string-ii/ 2. 题目描述 3. 题目大意 给定一个字符串,和字符串的间隔k, 这个k表示每k个数反转一次,然后再间隔k个元素再反转k个元素。 4. 解题思路 只要按照间隔去反转就可以了。然后间隔k个元素不反转是通过让i每次递增 2*k完成的。 5. AC代码 class Solution { ...

想当厨子的程序媛 211

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

LeetCode - 541 - 反转字符串II(reverse-string-ii)

一 目录 不折腾的前端,和咸鱼有什么区别目录一 目录二 前言三 解题及测试四 LeetCode Submit五 解题思路二 前言 难度:简单涉及知识:字符串题目地址:ht...

weixin_41806099的博客 223

541. Reverse String II*

541. Reverse String II* https://leetcode.com/problems/reverse-string-ii/ 题目描述 Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the star...

珍妮的选择的博客 280

leetcode[541]反转字符串II/reverse string II 反转字符串考察对代码的掌控能力

题目地址 https://leetcode-cn.com/problems/reverse-string-ii/ 思路 先做0344.反转字符串,在做这道题目更好一些 for循环中i 每次移动 2 * k,然后判断是否需要有反转的区间 C++代码 使用C++库里的反转函数reverse class Solution { public: string reverseStr(string s, int k) { for (int i = 0; i < s.size(); i +=

代码随想录 181

LeetCode 541. Reverse String II【字符串】简单

Given a string and an integer k , you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal

memcpy0的博客 632

541. Reverse String II

541. 反转字符串 II 给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。 示例: 输入: s = "abcdefg", k = 2 输出: "bacdfeg" 要求: ...

GGGGITFKBJG的主页 123

leetcode 541. Reverse String II 反转字符串 II

该题目要求对字符串进行每隔2k个字符反转前k个字符的处理。解决方案使用双指针法,将字符串分割为多个2k长度的区间,对每个区间的前k个字符进行反转。通过维护左右指针l和r来划定处理范围,判断剩余字符数是否足够k个来决定反转范围。最后将处理后的子字符串拼接得到最终结果。时间复杂度O(n),空间复杂度O(n)。

邹九的个人博客 408

541. 反转字符串 II(javascript)541. Reverse String II

541. 反转字符串 II(javascript)541. Reverse String II

ingenuou_的博客 1398

【Leetcode】541. Reverse String II

题目地址: https://leetcode.com/problems/reverse-string-ii/ 给定一个字符串,再给定一个正整数kkk。执行如下操作,对每2k2k2k个字符,翻转前kkk个;如果剩余数量小于kkk个,则将剩余全部翻转;如果剩余数量大于等于kkk个但不足2k2k2k个,则翻转前kkk个。代码如下: public class Solution { public S...

数学、算法爱好者的博客 304

leetcode 541. Reverse String II 简单题也得多刷刷

leetcode  541. Reverse String II class Solution(object): def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ return s

独钓寒江雪 380

leetcode 541 Reverse String II C++

这题没什么难的,读懂题就好了,注意k比字符串长和最后剩下的比k小的情况。 string reverseStr(string s, int k) { int pos = 0; while(pos < s.size()) { if (pos + k > s.size()) { k = s.size() -

wcxdell的专栏 1245
上一篇: markdown编辑器使用方法
下一篇: [LeetCode]543. Diameter of Binary Tree(计算二叉树的直径的长度)
whl_program
博客等级 码龄11年 101粉丝 279原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值