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;
    }
};
相关推荐
whxnchy13 小时前
UDP多端口负载均衡实战
c++
上海合宙LuatOS13 小时前
Air780EPM通过MQTT上传温湿度数据
开发语言·人工智能·物联网·junit·luatos
sheeta199814 小时前
LeetCode 每日一题笔记 日期:2026.05.08 题目:3629. 素数跳跃最小次数
笔记·算法·leetcode
叼烟扛炮14 小时前
C++ 知识点08 类与对象
开发语言·c++·算法·类和对象
米粒114 小时前
力扣算法刷题 Day 63 Bellman_ford 算法
数据库·算法·leetcode
楼田莉子14 小时前
仿Muduo的高并发服务器:Http协议模块
linux·服务器·c++·后端·学习
你不是我我20 小时前
【Java 开发日记】HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·开发语言·微服务
IT大白鼠21 小时前
AIGC性能的关键瓶颈:算力、数据、算法三者如何互相制约?
算法·aigc
tjl521314_2121 小时前
04C++ 名称空间(Namespace)
开发语言·c++
ximu_polaris21 小时前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式