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;
    }
};
相关推荐
阿正的梦工坊3 小时前
JavaScript 微任务与宏任务完全指南
开发语言·javascript·ecmascript
励志的小陈4 小时前
数据结构--二叉树知识讲解
数据结构
知行合一。。。4 小时前
Python--05--面向对象(属性,方法)
android·开发语言·python
自信150413057594 小时前
重生之从0开始学习c++之模板初级
c++·学习
leobertlan4 小时前
好玩系列:用20元实现快乐保存器
android·人工智能·算法
青梅橘子皮4 小时前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
笨笨饿4 小时前
#58_万能函数的构造方法:ReLU函数
数据结构·人工智能·stm32·单片机·硬件工程·学习方法
浅时光_c5 小时前
3 shell脚本编程
linux·开发语言·bash
历程里程碑5 小时前
2. Git版本回退全攻略:轻松掌握代码时光机
大数据·c++·git·elasticsearch·搜索引擎·github·全文检索
极客智造5 小时前
深度解析 C++ 类继承与多态:面向对象编程的核心
c++