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;
    }
};
相关推荐
Pniubi8 分钟前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
青少儿编程课堂35 分钟前
第十八届蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园三消乐大挑战解析
c++·python·算法·bfs·信息学竞赛
普通人640 分钟前
PHP多维数组排序完全指南
开发语言·php·1024程序员节
青少儿编程课堂1 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:网格连通块与岛屿数量(DFS+BFS双解)
c++·python·算法·bfs·信息学竞赛
码客-ygluu9 小时前
X3 LUA 异步分布式微服务集群框架
c++·架构·lua
starzy199010 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y11 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
forest_0912 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
九英里路12 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
吴可可12312 小时前
WScript Shell操作注册表详解
开发语言