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;
    }
};
相关推荐
aaaameliaaa6 小时前
字符函数和字符串函数
c语言·笔记·算法
微学AI7 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
城管不管7 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯8 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡8 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯8 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang8 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
韭菜炒鸡肝天8 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
The Chosen One9858 小时前
高进度算法模板速记(待完善)
java·前端·算法
小王C语言9 小时前
【7. 实现登录注册模块】:实现会话管理、注册/登录/退出 API
网络·c++