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;
    }
};
相关推荐
智码看视界2 分钟前
老梁聊全栈系列 JavaScript语言本质:从原型链到异步编程的深度解析
开发语言·javascript·全栈·javascript核心
AI科技星4 分钟前
数术工坊・八卷全书【本源创世终极版・万世定稿】
开发语言·网络·量子计算·拓扑学
雾沉川6 分钟前
Visual C++ 运行库合集 v105.0 部署与故障排查技术指南
开发语言·c++·dll
码云骑士7 分钟前
02-Python可变对象与不可变对象(上)-赋值陷阱与函数传参的暗坑
开发语言·python
不知名的老吴13 分钟前
经典算法题之行星碰撞
数据结构·算法
gaohe26AIliuzeyu16 分钟前
Java内部类
java·开发语言
AI科技星18 分钟前
数术工坊・八卷全书(番外・实战升华副卷)【终极典藏定稿|完整无删减】
c语言·开发语言·网络·量子计算·agi
丘山望岳19 分钟前
剑起霜华——平衡二叉树(AVL树 )精讲
开发语言·数据结构·c++
西安邮电大学20 分钟前
有关数组的经典算法题
java·后端·其他·算法·面试
yyuuuzz20 分钟前
云服务器软件部署的几个常见问题
运维·服务器·开发语言·网络·云计算·php·apache