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;
    }
};
相关推荐
热心网友俣先生3 分钟前
2026年华数杯C 题 超详细解题思路
c语言·开发语言·人工智能
啄缘之间16 分钟前
5.1 uvm‑component 的层级结构管理? new (name,parent) 参数
开发语言·笔记·学习·ic·uvm·sv
鹿角片ljp22 分钟前
LeetCode 53. 最大子数组和
算法·leetcode·职场和发展
旖旎夜光30 分钟前
C++(类与对象)(下)
开发语言·c++·学习
张小凡vip37 分钟前
Python爬虫实战:高效稳定的文件下载模块设计与实现
开发语言·爬虫·python
江屿风37 分钟前
【科普】【差集&交集概念落地云相册】流食般投喂
开发语言·c++·笔记·算法·云相册
数模竞赛Paid answer39 分钟前
2023年五一杯数学建模A题无人机定点投放问题求解全过程完整文档及程序
算法·数学建模·无人机·五一杯
代龙涛41 分钟前
WordPress header.php 与 footer.php 模板结构详解
开发语言·php·wordpress
科学实验家1 小时前
dp子序列问题,好难呀
算法
黄贵根6 小时前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript