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;
    }
};
相关推荐
鲸渔38 分钟前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
星恒随风1 小时前
从0实现C++ AI大模型接入SDK(三):环境搭建与ChatSDK快速上手——实现我们的第一个AI聊天程序
linux·开发语言·c++·人工智能·笔记
风落青芜1 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z1 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah2 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
fengkai45452 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
撸码猿2 小时前
Ladybird 进入 alpha:从零写的浏览器引擎现在能下载了
c++·rust·开源·浏览器·ladybird
草履虫AI课2 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
AAA修煤气灶刘哥3 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法
ShineWinsu3 小时前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤