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;
    }
};
相关推荐
Wect2 小时前
LeetCode 39. 组合总和:DFS回溯解法详解
前端·算法·typescript
Wect2 小时前
LeetCode 46. 全排列:深度解析+代码拆解
前端·算法·typescript
颜酱2 小时前
Dijkstra 算法:从 BFS 到带权最短路径
javascript·后端·算法
xlp666hub3 小时前
C++ 链表修炼指南
数据结构·c++
木心月转码ing5 小时前
Hot100-Day24-T128最长连续序列
算法
小肥柴5 小时前
A2UI:面向 Agent 的声明式 UI 协议(三):相关概念和技术架构
算法
学高数就犯困7 小时前
性能优化:LRU缓存(清晰易懂带图解)
算法
xlp666hub10 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode
CoovallyAIHub10 小时前
CVPR 2026 | MixerCSeg:仅2.05 GFLOPs刷新四大裂缝分割基准!解耦Mamba隐式注意力,CNN+Transformer+Mamba三
深度学习·算法·计算机视觉
CoovallyAIHub10 小时前
YOLO26-Pose 深度解读:端到端架构重新设计,姿态估计凭什么跨代领先?
深度学习·算法·计算机视觉