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;
    }
};
相关推荐
牛奔5 小时前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
m沐沐5 小时前
【深度学习】YOLOv2目标检测算法——改进点、网络结构与聚类先验框解析
人工智能·pytorch·深度学习·算法·yolo·目标检测·transformer
不会就选b5 小时前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
geovindu6 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
学逆向的6 小时前
汇编——JCC指令
开发语言·汇编·网络安全
mayaairi7 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
kite01217 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
稚南城才子,乌衣巷风流8 小时前
块状链表:数据结构详解与实现
数据结构·链表
Zachery Pole8 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米8 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展