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;
    }
};
相关推荐
Tony Bai40 分钟前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20241 小时前
Swift 类型转换
开发语言
前端小L1 小时前
贪心算法专题(十):维度权衡的艺术——「根据身高重建队列」
javascript·算法·贪心算法
方得一笔1 小时前
自定义常用的字符串函数(strlen,strcpy,strcmp,strcat)
算法
秃了也弱了。1 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730502 小时前
java数组整理笔记
java·开发语言·笔记
Xの哲學2 小时前
Linux SMP 实现机制深度剖析
linux·服务器·网络·算法·边缘计算
Thera7772 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
linux开发之路2 小时前
C++高性能日志库开发实践
c++·c++项目·后端开发·c++新特性·c++校招
wuk9982 小时前
使用PCA算法进行故障诊断的MATLAB仿真
算法·matlab