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;
    }
};
相关推荐
放羊郎4 分钟前
基于ORB-SLAM2算法的优化工作
人工智能·算法·计算机视觉
mask哥11 分钟前
力扣算法java实现汇总整理(上)
java·算法·leetcode
2zcode14 分钟前
运动模糊图像复原的MATLAB仿真与优化
开发语言·matlab
袁雅倩199725 分钟前
当吸尘器、筋膜枪都用上Type-C,供电方案该怎么选?浅谈PD取电芯片ECP5702的应用
c语言·开发语言·支持向量机·动态规划·推荐算法·最小二乘法·图搜索算法
如果'\'真能转义说1 小时前
OOXML 文档格式剖析:哈希、ZIP结构与识别
xml·算法·c#·哈希算法
夏日听雨眠1 小时前
数据结构(栈和队列)
数据结构
Aaswk1 小时前
Java Lambda 表达式与流处理
java·开发语言·python
万邦科技Lafite2 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
王老师青少年编程2 小时前
csp信奥赛C++高频考点专项训练之字符串 --【子串查找】:[NOIP 2009 提高组] 潜伏者
c++·字符串·csp·高频考点·信奥赛·子串查找·潜伏者
Cyber4K3 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php