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 分钟前
chap 8排序
算法·蓝桥杯·排序算法·软件工程
richdata10 分钟前
需求预测终极指南:零售商品预测方法、算法与AI实践
人工智能·算法·零售
神仙别闹15 分钟前
基于C++ 实现 BP 神经网络
开发语言·c++·神经网络
疯狂成瘾者31 分钟前
Java 集合 LinkedList 详解:链表结构、常用方法和队列使用
java·开发语言·链表
云梦泽࿐้35 分钟前
变量与数据类型:Python世界的基石
开发语言·python
QK_0036 分钟前
C语言 static 关键字三大作用
c语言·开发语言
隔窗听雨眠38 分钟前
C语言函数递归从入门到精通(下):性能优化与工程实践
c语言·算法·性能优化
开发小能手-roy42 分钟前
Lambda表达式性能陷阱:避坑指南与JIT编译优化分析
开发语言·python
退休倒计时44 分钟前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
珊瑚里的鱼1 小时前
【递归】汉诺塔
算法·深度优先