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;
    }
};
相关推荐
地平线开发者7 分钟前
征程6 MCU safetylib sample
算法·自动驾驶
Elastic 中国社区官方博客8 分钟前
用于 Elasticsearch 的 Gemini CLI 扩展,包含工具和技能
大数据·开发语言·人工智能·elasticsearch·搜索引擎·全文检索
Barkamin11 分钟前
归并排序的简单实现
数据结构
老赵的博客12 分钟前
qwebengineview 锲入网页并关闭
c++
wjs202413 分钟前
Bootstrap4 提示框详解
开发语言
biter down17 分钟前
C++ 单例模式:饿汉与懒汉模式
开发语言·c++·单例模式
echome88821 分钟前
Go 语言并发编程实战:用 Goroutine 和 Channel 构建高性能任务调度器
开发语言·后端·golang
l1t31 分钟前
与系统库同名python脚本文件引起的奇怪错误及其解决
开发语言·数据库·python
Jackey_Song_Odd36 分钟前
Part 1:Python语言核心 - 内建数据类型
开发语言·python
切糕师学AI43 分钟前
编程语言 Erlang 简介
开发语言·erlang