LeetCode541. Reverse String II

文章目录

一、题目

541. Reverse String II

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer 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 leave the other as original.

Example 1:

Input: s = "abcdefg", k = 2

Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2

Output: "bacd"

Constraints:

1 <= s.length <= 104

s consists of only lowercase English letters.

1 <= k <= 104

二、题解

cpp 复制代码
class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.length();
        //循环处理2k个单位
        for(int i = 0;i < n;i += 2 * k){
            if(i + k <= n){
                reverse(s.begin() + i,s.begin() + i + k);
            }
            else reverse(s.begin() + i,s.end());
        }
        return s;
    }
};
相关推荐
_dindong2 分钟前
仿muduo库实现高并发服务器 -通用类型Any类型的实现
服务器·c++
xpbobcsdn22 分钟前
JDK 28 值类:省一半内存,慢三成
java·开发语言
承渊政道28 分钟前
【Python编程快速上手—让繁琐工作自动化】(组织文件:用Python批量改名,把整个文件夹打包备份)
开发语言·python·pycharm·自动化·文件整理·组织文件
默 语38 分钟前
HarmonyOS7 组件通用事件(二):onAppear / onDisAppear 挂载卸载事件——组件的“生死“只有 if 说了算
开发语言·php
不在逃避q39 分钟前
用生活里的小场景,一键打开 C++ 编程入门大门
开发语言·c++·生活
Shaoshing42 分钟前
LeetCode 1798. 你能构造出连续值的最大数目
java·数据结构·算法
YSL07012444 分钟前
C++string类详解
开发语言·数据结构·c++
迪康coolmu1 小时前
基于迪康端点安全一体化管理系统的刻录通道审计:刻录记录、类型识别与追溯路径
运维·开发语言·网络·经验分享·科技·安全·php
大今野1 小时前
江苏专转本计算机大类基础理论考点:算法的概念与复杂度分析
数据结构·算法·专转本
郝学胜-神的一滴1 小时前
量化交易从入门到精通 04:量化生意的四大特点
开发语言·数据结构·c++·python·算法·pycharm