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;
    }
};
相关推荐
Molesidy2 小时前
【VSCode】【Clangd】Win下的基于LLVM/Clangd+Clangd插件+MINGW+CMake的VSCode配置C/C++开发环境的详细教程
c++·ide·vscode·clangd·llvm
报错小能手3 小时前
刷题日常 5 二叉树最大深度
算法
ᐇ9593 小时前
Java LinkedList集合全面解析:双向链表的艺术与实战
java·开发语言·链表
码银3 小时前
【数据结构】顺序表
java·开发语言·数据结构
Greedy Alg3 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
Mr_WangAndy3 小时前
C++_chapter13_C++并发与多线程_多线程概念,死锁,unique_lock(),lock_guard()使用
c++·lock·死锁·并发与多线程·unlock·lock_guard·unique_lock
im_AMBER4 小时前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油4 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
神仙别闹4 小时前
基于QT(C++) 实现哈夫曼压缩(多线程)
java·c++·qt