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;
    }
};
相关推荐
kyle~2 小时前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
NiNi_suanfa5 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码5 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent6 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
信奥胡老师6 小时前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺6 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
风筝在晴天搁浅6 小时前
代码随想录 718.最长重复子数组
算法
kyle~6 小时前
算法---回溯算法
算法
Halo_tjn6 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen6 小时前
C++实现完美洗牌算法
开发语言·c++·算法