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;
    }
};
相关推荐
Dlrb12114 小时前
C语言-指针三
c语言·算法·指针·const·命令行参数
kkeeper~4 小时前
0基础C语言积跬步之深入理解指针(5下)
c语言·开发语言
Tisfy5 小时前
LeetCode 2540.最小公共值:双指针(O(m+n))
算法·leetcode·题解·双指针
一直不明飞行5 小时前
Java的equals(),hashCode()应该在什么时候重写
java·开发语言·jvm
IronMurphy5 小时前
【算法四十七】152. 乘积最大子数组
算法
REDcker5 小时前
有限状态机与状态模式详解 FSM建模Java状态模式与C++表驱动模板实践
java·c++·状态模式
盲敲代码的阿豪5 小时前
Python 入门基础教程(爬虫前置版)
开发语言·爬虫·python
basketball6165 小时前
C++ 构造函数完全指南:从入门到进阶
java·开发语言·c++
互联科技报5 小时前
2026超融合选型:Top5品牌与市场格局解读
开发语言·perl
weixin199701080166 小时前
[特殊字符] 智能数据采集:数字化转型的“数据石油勘探队”(附Python实战源码)
开发语言·python