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;
    }
};
相关推荐
王九思1 分钟前
Java 内存分析工具 MAT
java·开发语言·安全
AlenTech7 分钟前
197. 上升的温度 - 力扣(LeetCode)
算法·leetcode·职场和发展
superman超哥18 分钟前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
夕除24 分钟前
java--2
java·开发语言
橘颂TA35 分钟前
【Linux 网络】TCP 拥塞控制与异常处理:从原理到实践的深度剖析
linux·运维·网络·tcp/ip·算法·职场和发展·结构与算法
星辰徐哥43 分钟前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust
liliangcsdn44 分钟前
如何使用lambda对python列表进行排序
开发语言·python
tobias.b1 小时前
408真题解析-2010-9-数据结构-折半查找的比较次数
java·数据结构·算法·计算机考研·408真题解析
源代码•宸1 小时前
Leetcode—404. 左叶子之和【简单】
经验分享·后端·算法·leetcode·职场和发展·golang·dfs
WBluuue1 小时前
数据结构与算法:dp优化——优化尝试和状态设计
c++·算法·leetcode·动态规划