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;
    }
};
相关推荐
z2005093012 小时前
【linux学习】深入理解 Linux 进程间通信:管道的艺术与实现
linux·开发语言
星马梦缘12 小时前
算法设计与分析 作业三 答案与解析
算法·线性规划·二分图匹配·多元最短路·流网络·bellmanford·匈牙利树算法
lcj251112 小时前
【stack、queue、deque、priority_queue】C++ 栈 / 队列 / 优先级队列全解析!手撕实现 + 二叉树层序遍历(附源码)
开发语言·c++·笔记
微风欲寻竹影12 小时前
Java数据结构——二叉树相关OJ题目详解
java·数据结构
兵哥工控12 小时前
高精度微秒延时函数实现顺控工控项目实例
c++·mfc·硬件高精度计时器
微风欲寻竹影12 小时前
Java数据结构——二叉树(Binary Tree)详解
java·数据结构·算法
j_xxx404_12 小时前
Linux线程池硬核解析:从固定线程池、单例线程池到线程安全、死锁与锁模型|附源码
linux·运维·服务器·c++·安全·ai
想吃火锅100512 小时前
【leetcode】3.无重复字符的最长字串js版
算法·leetcode·职场和发展
smith成长之旅12 小时前
08 | Mem0 框架分析: BM25 的 Sigmoid 归一化
数据库·python·算法
牛油果子哥q12 小时前
【C++静态成员】C++静态成员终极精讲:静态成员变量、静态成员函数、内存布局、对象共享机制、工程实战、深浅坑点与面试满分总结
c++·面试