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;
    }
};
相关推荐
我是无敌小恐龙23 分钟前
Java基础入门Day10 | Object类、包装类、大数/日期类、冒泡排序与Arrays工具类 超详细总结
java·开发语言·数据结构·算法·贪心算法·排序算法·动态规划
ADI_OP36 分钟前
用SigmaStudio+软件来开发ADSP-21565
算法·音视频·adi dsp中文资料·adi音频dsp·adi dsp开发教程
yuanyuan2o239 分钟前
从最小项目开始的 CMake 教程
c语言·开发语言·arm开发·c++·makefile·make·cmake
lifewange41 分钟前
pytest 找不到文件?直接在 pytest.ini 配置根目录 + 路径(最简单方案)
开发语言·python·pytest
城事漫游Molly42 分钟前
研究设计核心 Toolkit:从“知道方法”到“真正会设计”
大数据·人工智能·算法·ai写作·论文笔记
大鹏说大话1 小时前
MySQL + Redis + Caffeine:Java后端通用三级缓存架构实战
开发语言
yuanpan1 小时前
Python 桌面 GUI 入门开发:从 tkinter 窗口到简易记事本
开发语言·python
User_芊芊君子1 小时前
聊聊自由开发者常用的学习机会全解析
开发语言·人工智能·python
流年如夢1 小时前
单链表的应用 --> 简单通讯录的实现
android·数据结构·链表