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;
    }
};
相关推荐
MarkHD几秒前
第一天 车联网定义、发展历程与生态体系
开发语言·php
百锦再5 分钟前
Python深度挖掘:openpyxl和pandas的使用详细
java·开发语言·python·框架·pandas·压力测试·idea
mooridy7 分钟前
设计模式 | 详解常用设计模式(六大设计原则,单例模式,工厂模式,建造者模式,代理模式)
c++·设计模式
microhex9 分钟前
Glide 如何加载远程 Base64 图片
java·开发语言·glide
chilling heart18 分钟前
JAVA---集合ArrayList
java·开发语言
import_random31 分钟前
[机器学习]xgboost和lightgbm(区别)
算法
梁辰兴31 分钟前
数据结构:实验7.3Huffman树与Huffman编码
数据结构·c++·算法·c
小_t_同学34 分钟前
C++之类和对象:构造函数,析构函数,拷贝构造,赋值运算符重载
开发语言·c++
wuqingshun31415934 分钟前
经典算法 最长单调递增子序列
java·c++·算法·蓝桥杯·机器人
企鹅chi月饼39 分钟前
动态规划问题,下降路径最小和(dp初始化问题,状态压缩),单词拆分(回溯法+剪枝+记忆化),substr函数
算法·动态规划