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;
    }
};
相关推荐
玛丽莲茼蒿2 分钟前
Leetcode hot100 在排序数组中查找元素的第一个和最后一个位置【中等】
数据结构·算法
会编程的土豆4 分钟前
洛谷题单 入门1 顺序结构(go语言)
开发语言·后端·golang·洛谷
jieyucx4 分钟前
Go 语言 switch 条件语句详解
开发语言·c++·golang
AC赳赳老秦5 分钟前
网安工程师提效:用 OpenClaw 实现漏洞扫描报告生成、安全巡检自动化、日志合规审计
java·开发语言·前端·javascript·python·deepseek·openclaw
墨染天姬6 分钟前
[AI]OPENAI的PPO算法
人工智能·算法
初心未改HD7 分钟前
Go语言defer机制深度解析
开发语言·golang
万法若空10 分钟前
C++ <iomanip> 库全方位详解
开发语言·c++
c++之路11 分钟前
C++ 模板
linux·开发语言·c++
幻影七幻11 分钟前
js中send的作用和使用 $.ajax的作用
开发语言·前端·javascript
鸿儒51716 分钟前
记录一个C++ Windows程序移植到Linux系统的bug
开发语言·c++·bug