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;
    }
};
相关推荐
软件开发技术深度爱好者15 小时前
Python库/包/模块管理工具
开发语言·python
小白程序员成长日记15 小时前
2025.11.21 力扣每日一题
算法·leetcode·职场和发展
bubiyoushang88815 小时前
基于MATLAB的自然图像梯度分布重尾特性验证方案
开发语言·matlab
MSTcheng.15 小时前
【C++STL】priority_queue 模拟实现与仿函数实战
开发语言·c++
还有几根头发呀15 小时前
从 C++ 的角度,系统地解释 进程(Process)、线程(Thread)、协程(Coroutine) 的概念、原理、优缺点,以及常见应用场景。
c++
oioihoii15 小时前
Python与C++:从哲学到细节的全面对比
c++
小年糕是糕手15 小时前
【C++】C++入门 -- inline、nullptr
linux·开发语言·jvm·数据结构·c++·算法·排序算法
郝学胜-神的一滴15 小时前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
高洁0116 小时前
具身智能-普通LLM智能体与具身智能:从语言理解到自主行动
人工智能·深度学习·算法·aigc·知识图谱
kk哥889916 小时前
Keil MDK 5.39 编程 + 调试 ,ARM 嵌入式开发!如何安装
c++·arm