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;
    }
};
相关推荐
我是一颗柠檬2 分钟前
C语言最全面复习:从入门到精通(2026年)
c语言·开发语言
小雨下雨的雨3 分钟前
鸿蒙PC用Electron框架 实现 房产交易系统核心算法深度解析
前端·javascript·算法·华为·electron·鸿蒙系统
ch.ju3 分钟前
Java Programming Chapter 4——The set method assigns a value to the property.
java·开发语言
CQU_JIAKE3 分钟前
6.3[a]
算法
此生决int3 分钟前
算法从入门到精通——字符串
数据结构·c++·算法·蓝桥杯
古城小栈4 分钟前
Rustix库:Rust 系统编程 的 基石
开发语言·后端·rust
bIo7lyA8v4 分钟前
算法复杂度下限证明与优化空间分析的技术8
算法
basketball6165 分钟前
设计模式入门:7. 策略模式详解 C++实现
c++·设计模式·策略模式
Luminous.6 分钟前
C语言--day26
c语言·开发语言
luj_17687 分钟前
硝酸体系核关联假说解析
服务器·c语言·开发语言·经验分享·算法