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;
    }
};
相关推荐
我的知识太少了12 小时前
P1122 最大子树和
算法
UrSpecial12 小时前
Linux线程
linux·开发语言·c++
郝学胜-神的一滴12 小时前
深入浅出 C++20:新特性与实践
开发语言·c++·程序人生·算法·c++20
汉克老师12 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.1.15]第二部分编程题(2 、寻宝石)
c++·蓝桥杯·蓝桥杯c++·c++蓝桥杯·蓝桥杯选拔赛
Jelena技术达人12 小时前
淘宝/天猫按图搜索(拍立淘)item_search_img API接口实战指南
算法·图搜索算法
大锦终12 小时前
【Linux】进程间通信
linux·运维·服务器·c++
闪电麦坤9512 小时前
C/C++项目练习:命令行记账本
开发语言·c++
Adorable老犀牛13 小时前
阿里云-基于通义灵码实现高效 AI 编码 | 8 | 上手实操:LeetCode学习宝典,通义灵码赋能算法高效突破
学习·算法·leetcode
kyle~13 小时前
python---PyInstaller(将Python脚本打包为可执行文件)
开发语言·前端·python·qt
望获linux13 小时前
【实时Linux实战系列】规避缺页中断:mlock/hugetlb 与页面预热
java·linux·服务器·数据库·chrome·算法