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;
    }
};
相关推荐
承渊政道1 小时前
C++学习之旅【C++类和对象(下)】
c++·学习·visual studio
枫叶丹41 小时前
【Qt开发】Qt窗口(九) -> QFontDialog 字体对话框
c语言·开发语言·数据库·c++·qt
海上彼尚2 小时前
Go之路 - 7.go的结构体
开发语言·后端·golang
源代码•宸7 小时前
分布式缓存-GO(分布式算法之一致性哈希、缓存对外服务化)
开发语言·经验分享·分布式·后端·算法·缓存·golang
云和数据.ChenGuang7 小时前
PHP-FPM返回的File not found.”的本质
开发语言·php·运维工程师·运维技术
R.lin7 小时前
Java 8日期时间API完全指南
java·开发语言·python
旖旎夜光8 小时前
多态(11)(下)
c++·学习
yongui478348 小时前
MATLAB的指纹识别系统实现
算法
高山上有一只小老虎8 小时前
翻之矩阵中的行
java·算法
yangpipi-8 小时前
《C++并发编程实战》 第4章 并发操作的同步
开发语言·c++