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;
    }
};
相关推荐
一条破秋裤1 分钟前
C-数据类型
c语言·开发语言·chrome
君顾17 分钟前
从0到1课后辅导管理系统开发实战:需求文档、架构设计全复盘
java·开发语言
神仙别闹8 分钟前
基于C++ MFC RSA 实现加密程序
开发语言·c++·mfc
HanhahnaH21 分钟前
各数据结构操作的时间复杂度汇总
数据结构·算法
增量星球23 分钟前
一个 Python 脚本 + LLM 怎么替代向量检索?ProjQA 技能架构原理深度解析
开发语言·python·架构·embedding·skill
Yzzz-F32 分钟前
CF2023D
c++·算法·dp
_wxd66636 分钟前
排序-堆排序(Heap Sort)
数据结构
探数API小喇叭40 分钟前
基站查询 API 怎么用?LAC、CELLID 参数详解与实战】
java·开发语言·api·基站定位
小小帅呀41 分钟前
学习 VLA 第6天:SWIN VIT算法原理以及复现
学习·算法
Mr.Lu ‍42 分钟前
C++开发,使用openCV API对图片进行压缩
开发语言·c++·opencv