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;
    }
};
相关推荐
一直C1 分钟前
【Linux应用编程】深入理解Linux多任务机制:进程原理、状态转换与进程控制实战
linux·开发语言·算法·ubuntu·vim·visual studio code
qz5zwangzihan12 分钟前
AtCoder高频英文词汇短语
c++·atcoder·高频词
码匠许师傅11 分钟前
【C++ 面试真题】聊聊 C++ 的类型特征( type_traits)
java·c++·面试
名字还没想好☜12 分钟前
Python asyncio.Queue 实战:用生产者-消费者给爬虫/任务流限速又解耦
开发语言·爬虫·python·并发·asyncio
小小龙学IT17 分钟前
C++ 性能优化:CPU 缓存与数据布局优化深度解析
c++·缓存·性能优化
玉树临风ives32 分钟前
atcoder ABC 472 题解
数据结构·c++·算法
AI服务老曹38 分钟前
抽烟识别算法接入 AI 视频分析平台的流程与误报优化指南
人工智能·算法·音视频
阳明山水41 分钟前
销量预测2025—2026:技术演进、实证发现与系统架构的系统性综述
人工智能·深度学习·算法·机器学习·架构
伯远医学1 小时前
RIP-seq 高分文献案例分享
java·前端·javascript·人工智能·算法·eclipse·html