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;
    }
};
相关推荐
Trouvaille ~3 分钟前
【Linux】网络编程基础(二):数据封装与网络传输流程
linux·运维·服务器·网络·c++·tcp/ip·通信
Next_Tech_AI11 分钟前
别用 JS 惯坏了鸿蒙
开发语言·前端·javascript·个人开发·ai编程·harmonyos
chillxiaohan15 分钟前
GO学习记录——多文件调用
开发语言·学习·golang
2301_8223663519 分钟前
C++中的命令模式变体
开发语言·c++·算法
一刻钟.21 分钟前
C#高级语法之线程与任务
开发语言·c#
追逐梦想的张小年36 分钟前
JUC编程03
java·开发语言·idea
派葛穆37 分钟前
Python-PyQt5 安装与配置教程
开发语言·python·qt
每天要多喝水38 分钟前
nlohmann/json 的使用
c++·json
小乔的编程内容分享站1 小时前
记录使用VSCode调试含scanf()的C语言程序出现的两个问题
c语言·开发语言·笔记·vscode
toooooop81 小时前
php BC MATH扩展函数计算精度-第三个参数
开发语言·php