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;
    }
};
相关推荐
EW Frontier14 分钟前
6G ISAC新范式:基于智能漏波天线的Wi‑Fi通感一体化系统设计与实测【附MATLAB+python代码】
开发语言·python·matlab·music·isac·doa·wi‑fi
贾斯汀玛尔斯21 分钟前
每天学一个算法--倒排索引(Inverted Index)
算法·inverted-index
楼田莉子24 分钟前
Linux网络:NAT_代理
linux·运维·服务器·开发语言·c++·后端
小e说说24 分钟前
打破偏科困境:这些学习软件助孩子重燃学习热情
算法
南境十里·墨染春水30 分钟前
C++日志 2——实现单线程日志系统
java·jvm·c++
froginwe1133 分钟前
jEasyUI 创建基础树形网格
开发语言
zh_xuan38 分钟前
api测试工具添加历史记录功能
c++·libcurl·duilib
月昤昽1 小时前
autoCAD二次开发 4.正多边形与collection区分
算法·c#·二次开发·autocad二次开发
休息一下接着来1 小时前
C++ 固定容量环形队列实现
c++·算法
Victory_20251 小时前
c#定时器顺序控制写法
开发语言·c#·c#顺序控制+定时器