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;
    }
};
相关推荐
t***5445 小时前
Clang 编译器在 Orwell Dev-C++ 中的局限性
开发语言·c++
Sam_Deep_Thinking6 小时前
学数据结构到底有什么用
数据结构
oy_mail6 小时前
QoS质量配置
开发语言·智能路由器·php
oyzz1206 小时前
PHP操作redis
开发语言·redis·php
kobesdu6 小时前
人形机器人SLAM:技术挑战、算法综述与开源方案
算法·机器人·人形机器人
nashane6 小时前
HarmonyOS 6学习:网络能力变化监听与智能提示——告别流量偷跑,打造贴心网络感知应用
开发语言·php·harmony app
yolo_guo7 小时前
redis++使用: hmset 与 hmget
c++·redis
凌波粒7 小时前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
handler017 小时前
拒绝权限报错!三分钟掌握 Linux 权限管理
linux·c语言·c++·笔记·学习
拾贰_C7 小时前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua