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;
    }
};
相关推荐
让我们一起加油好吗29 分钟前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
时间的情敌38 分钟前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
路灯中转站39 分钟前
数据结构C语言版(什么是数据类型)
数据结构
凌冰_1 小时前
数据结构 - 队列(五)
数据结构·算法·软件工程
Amumu121381 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
sul.i1 小时前
浅析 · 分治
c++
让我们一起加油好吗2 小时前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
敲上瘾2 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
船神丿男人2 小时前
C++ STL 入门:用 std::string 读配置,四个容易漏掉的边界
开发语言·c++
让我们一起加油好吗3 小时前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试