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;
    }
};
相关推荐
mjhcsp4 分钟前
透彻背包DP:从DFS暴力搜索到动态规划的逐步推导
算法·深度优先·动态规划
电商API&Tina5 分钟前
Python请求淘宝商品评论API接口全指南||taobao评论API
java·开发语言·数据库·python·json·php
学嵌入式的小杨同学8 分钟前
【嵌入式 C 语言实战】交互式栈管理系统:从功能实现到用户交互全解析
c语言·开发语言·arm开发·数据结构·c++·算法·链表
txinyu的博客9 分钟前
static_cast、const_cast、dynamic_cast、reinterpret_cast
linux·c++
多米Domi01110 分钟前
0x3f 第40天 setnx的分布式锁和redission,写了一天项目书,光背了会儿八股,回溯(单词搜索)
数据结构·算法·leetcode
乐迪信息11 分钟前
乐迪信息解决港口船型识别难题!AI算法盒子检测船舶类型
人工智能·算法·智能电视
“αβ”23 分钟前
TCP相关实验
运维·服务器·网络·c++·网络协议·tcp/ip·udp
小杍随笔25 分钟前
【Rust Cargo 目录迁移到 D 盘:不改变安装路径和环境变量的终极方案】
开发语言·后端·rust
梭七y27 分钟前
【力扣hot100题】(151)课程表
算法·leetcode·哈希算法
Henry Zhu1231 小时前
Qt Model/View架构详解(五):综合实战项目
开发语言·qt·架构