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;
    }
};
相关推荐
geovindu6 分钟前
go: Task Scheduler
开发语言·后端·golang
kiracrimson24 分钟前
【无标题】
数据结构
会飞的拖把27 分钟前
Python 多任务编程:并发、进程、线程与线程安全详解
开发语言·python
君顾135 分钟前
折扣卡 CPS 小程序定制:从业务流程到系统架构的实践指南
java·开发语言·折扣卡
老赵的博客1 小时前
c++ 之观察者模式
c++·qt
坚定学代码1 小时前
static在c++中的使用
开发语言·c++
hansang_IR2 小时前
【题解】P5364 [SNOI2017] 礼物
c++·线性代数·算法
Tisfy2 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
无小道2 小时前
C/C++——tuple小记
c++·tuple
小O的算法实验室2 小时前
IEEE TEVC,基于K-means与DQN辅助元启发式算法的多目标两栖无人艇调度模型
算法·kmeans·启发式算法