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;
    }
};
相关推荐
tumu_C11 分钟前
用std::function减缓C++模板代码膨胀和编译压力的一个场景
开发语言·c++
BT-BOX24 分钟前
Matlab 2025B下载安装教程
开发语言·matlab
Hical611 小时前
C++17 实战心得:那些真正改变我写代码方式的特性
c++
programhelp_1 小时前
Pinterest OA 题库大公开|Programhelp 独家整理(最新高频)
java·开发语言
他是龙5511 小时前
71:Python安全 & 反序列化 & PYC反编译 & 格式化字符串安全
开发语言·python·安全
YXXY3132 小时前
模拟算法的介绍
算法
Hical612 小时前
实测:C++20 协程 vs Go Gin vs Rust Actix,谁的 Web 性能更强?
c++
wjs20242 小时前
Go 语言接口
开发语言
happymaker06262 小时前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
草莓熊Lotso2 小时前
《告别 “会用不会讲”:C++ string 底层原理拆解 + 手撕实现,面试 / 开发都适用》
开发语言·c++·面试