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;
    }
};
相关推荐
Hui Baby几秒前
LSM 原理、实现及与 B+ 树的核心区别
java·linux·算法
NZT-48几秒前
C++基础笔记(二)队列deque,queue和堆priority_queue
java·c++·笔记
艾上编程5 分钟前
第三章——爬虫工具场景之Python爬虫实战:行业资讯爬取与存储,抢占信息先机
开发语言·爬虫·python
β添砖java13 分钟前
python第一阶段第10章
开发语言·python
爬山算法17 分钟前
Netty(13)Netty中的事件和回调机制
java·前端·算法
hweiyu0023 分钟前
数据结构:广义表
数据结构
CoovallyAIHub23 分钟前
是什么支撑L3自动驾驶落地?读懂AI驾驶与碰撞预测
深度学习·算法·计算机视觉
玉树临风ives30 分钟前
atcoder ABC436 题解
c++·算法·leetcode·atcoder·信息学奥赛
fpcc32 分钟前
C++23中的自定义模块开发
c++·c++23
圣保罗的大教堂34 分钟前
leetcode 2110. 股票平滑下跌阶段的数目 中等
leetcode