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;
    }
};
相关推荐
神威难绷泪2 分钟前
数据结构:哈希表 算法相关 排序算法
数据结构
程序猿阿森3 分钟前
Python 闭包与装饰器:从入门到精通
开发语言·python·面试
艾为电子12 分钟前
【应用方案】电视沉浸式音频升级: 电视音频 awinic“芯片 + 算法” 一体化解决方案
算法·音视频
余额瞒着我当琳16 分钟前
C++--vector底层,leetcode118杨辉三角实战,对于传统reserve的坑点,迭代器失效
开发语言·c++
曹牧19 分钟前
C#:字符串做20位截断
开发语言·c#
大熊背27 分钟前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
醉城夜风~38 分钟前
(超详细)C++多态(Polymorphism)
开发语言·c++
这是个栗子41 分钟前
【JS代码分析】前端鉴权基础:Token 的本地存储与状态重置实践
开发语言·前端·javascript
Scabbards_44 分钟前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai1 小时前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法