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;
    }
};
相关推荐
野生技术架构师8 分钟前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
袋鼠云数栈10 分钟前
集团数字化统战实战:统一数据门户与全业态监管体系构建
大数据·数据结构·人工智能·多模态
Q一件事32 分钟前
R语言制图-相关性及关系网络图
开发语言·r语言
坊钰35 分钟前
Java 死锁问题及其解决方案
java·开发语言·数据库
小月球~1 小时前
天梯赛 · 并查集
数据结构·算法
仍然.1 小时前
算法题目---模拟
java·javascript·算法
551只玄猫2 小时前
【数学建模 matlab 实验报告1】
开发语言·数学建模·matlab·课程设计·实验报告
史蒂芬_丁2 小时前
Qt, C++数据类型扩展问题
数据库·c++·qt
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 118. 杨辉三角 | C++ 动态规划题解
c++·leetcode·动态规划
三道渊3 小时前
C语言:文件I/O
c语言·开发语言·数据结构·c++