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;
    }
};
相关推荐
WL学习笔记7 分钟前
日期类(C++)
开发语言·c++·日期类实现
谢亮_vipxieliang1 小时前
Go map与结构体的正确使用
开发语言·golang·哈希算法
H.莓飛1 小时前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
一只小小的芙厨1 小时前
【线性DP】
学习·算法·动态规划
xxwl5851 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构
奋发向前wcx1 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法
汉克老师2 小时前
GESP2026年9月认证C++八级( 第一部分选择题(1~7题)精讲
c++·gesp·小学生·学c++编程
罗湖老棍子3 小时前
C Looooops(信息学奥赛一本通- P1640)
算法·数论·同余·裴蜀定理·扩展欧几里得
郝学胜_神的一滴4 小时前
C++ Templates 06:搞懂模板代码的三种组织方式
c++·visual studio
C++ 老炮儿的技术栈4 小时前
sizeof操作符
c语言·c++·人工智能·mfc·c