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;
    }
};
相关推荐
m0_380743874 分钟前
PHP7.3和7.2字符串功能有什么不同
开发语言·php
All for pursuit.30 分钟前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
m0_3807438739 分钟前
PHP 8.4的新语法怎么用才规范
开发语言·php
头发够用的程序员42 分钟前
TensorRT 自定义算子插件实战(一):从零手写 customScaledTanh
c++·人工智能·pytorch·python·深度学习·边缘计算·jetson
哭泣方源炼蛊1 小时前
正则表达式c++内容汇集
数据库·c++·mysql·正则表达式
索尔~古德曼1 小时前
CF(1400-1400&1300-1500)错题集
算法
阿狗童鞋1 小时前
Java并发编程实战指南
java·开发语言
别动我齐刘海1 小时前
简历技术栈全面复习——UDP / TCP / CAN / ZMQ / Protobuf 通信工程
网络·c++·python·tcp/ip·机器学习·udp·github
phltxy1 小时前
C 语言自定义类型:结构体、位段、枚举与联合体
c语言·开发语言
Sarvartha2 小时前
对象创建与引用
java·开发语言