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;
    }
};
相关推荐
wuyk5551 分钟前
Python 零基础入门第九章:用户输入与 While 循环
开发语言·python
兮动人5 分钟前
Python变量与常量
开发语言·python·机器学习·python变量与常量
风筝在晴天搁浅13 分钟前
解题代码清爽版
java·开发语言
Java后端的Ai之路20 分钟前
21、Python - 命令模式
开发语言·人工智能·python·命令模式·外观模式
小小晓.22 分钟前
C++单例模式万字详解:6种实现演进+线程安全彻底解决+CRTP终极模板
c++·单例模式
astronautyi25 分钟前
Go 运行时内存分配与 GC 位图深度剖析
开发语言·后端·golang
techdashen32 分钟前
Go 中如何处理错误
开发语言·后端·golang
孙克旭_1 小时前
JVM 入门详解:JVM、JRE、JDK 区别,JVM 基础结构梳理
java·开发语言·jvm
随遇而安zx1 小时前
【地基篇】---JVM 内存结构知识点(Java 8 运行时数据区深度解析)
java·开发语言·jvm
FfHUCisI1 小时前
Golang 切片扩容策略
开发语言·数据库·golang