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;
    }
};
相关推荐
wearegogog1231 分钟前
基于Q-learning的栅格地图路径规划MATLAB仿真程序
开发语言·算法·matlab
旖-旎4 分钟前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣
T0uken12 分钟前
基于 vcpkg 与 LLVM-MinGW 的 Qt6 静态链接开发方案
c++·windows·qt
睡一觉就好了。14 分钟前
C++11(一)
c++
小O的算法实验室15 分钟前
2026年ASOC,基于人工势场的差分进化算法改进框架,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
xieliyu.16 分钟前
Java手搓数据结构:从零模拟实现无头双向非循环链表
java·数据结构·链表
csbysj202017 分钟前
Java 条件语句
开发语言
爱学习的张大20 分钟前
具身智能论文精读(五):OpenVLA
人工智能·算法
水云桐程序员31 分钟前
C++的主要应用场景
c++·学习方法
Ulyanov1 小时前
《现代 Python 桌面应用架构实战:PySide6 + QML 从入门到工程化》 开发环境搭建与工具链极简主义 —— 拒绝臃肿,构建工业级基座
开发语言·python·qt·ui·架构·系统仿真