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;
    }
};
相关推荐
CDN3607 分钟前
[硬核] 你的DNS正在“裸奔”?用Python手撕DNS劫持与隧道检测逻辑
开发语言·网络·python
froginwe1111 分钟前
jQuery 添加元素
开发语言
zh_xuan11 分钟前
api测试工具支持代理
c++·libcurl
zhangfeng113314 分钟前
PHP 语法检查命令 php -l “$file“ > /dev/null 2>&1;
开发语言·php
csbysj202015 分钟前
解释器模式
开发语言
夜猫逐梦16 分钟前
[开发经验] DLL注入中控制台窗口无法关闭的排查与修复
c++·windows·控制台
无限进步_23 分钟前
C++ 多态机制完全解析:从虚函数重写到动态绑定原理
java·c语言·jvm·数据结构·c++·windows·后端
CoderCodingNo31 分钟前
【信奥业余科普】C++ 的奇妙之旅 | 20:更安全的间接访问——引用的设计动机与实战对比
开发语言·c++
小O的算法实验室34 分钟前
2026年ESWA,基于固定机巢的无人机输电杆塔、变电站与配电杆混合巡检任务分配与路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
知识汲取者1 小时前
巨量引擎 Marketing API Java SDK 介绍
java·开发语言