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;
    }
};
相关推荐
changshuaihua0011 分钟前
useState 状态管理
开发语言·前端·javascript·react.js
聆风吟º4 分钟前
【Python编程日志】Python入门基础(二):行 | 缩进 | print输出
开发语言·python·print··缩进
lsx2024067 分钟前
Servlet 点击计数器
开发语言
卷心菜狗9 分钟前
Python进阶-闭包与装饰器
开发语言·python·学习
MegaDataFlowers12 分钟前
3.无重复字符的最长子串
算法
凯瑟琳.奥古斯特12 分钟前
C++变量命名进阶技巧
开发语言·c++
不羁的fang少年13 分钟前
Netty网络模型
java·开发语言
人道领域18 分钟前
【LeetCode刷题日记】20.有效的括号
算法·leetcode·职场和发展
生信研究猿18 分钟前
#P3492.第1题-基于决策树预判资源调配优先级
python·算法·决策树
贾斯汀玛尔斯19 分钟前
每天学一个算法--缓存淘汰策略(LRU / LFU · 结构与复杂度)
算法·缓存