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;
    }
};
相关推荐
漫随流水4 分钟前
leetcode算法(104.二叉树的最大深度)
数据结构·算法·leetcode·二叉树
matlabgoodboy10 分钟前
程序代做python代编程matlab定制代码编写C++代写plc设计java帮做
c++·python·matlab
机器学习之心HML18 分钟前
鲸鱼算法(WOA)优化Kriging模型
算法
DYS_房东的猫27 分钟前
《 C++ 零基础入门教程》第6章:模板与 STL 算法 —— 写一次,用万次
开发语言·c++·算法
Tim_1028 分钟前
【算法专题训练】37、前缀树&二叉树
算法
诗意地回家34 分钟前
淘宝小游戏反编译
开发语言·前端·javascript
wangkay8841 分钟前
【Java 转运营】Day04:抖音新号起号前准备全指南
java·开发语言·新媒体运营
点云SLAM41 分钟前
C++ 静态初始化顺序问题(SIOF)和SLAM / ROS 工程实战问题
开发语言·c++·slam·静态初始化顺序问题·工程实战技术·c++static 关键字
NineData42 分钟前
第三届数据库编程大赛-八强决赛成绩揭晓
数据库·算法·代码规范
D3bugRealm42 分钟前
MATLAB解决物理问题:从基础运动学到进阶力学的实战指南
开发语言·其他·matlab