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;
    }
};
相关推荐
豆豆的java之旅2 分钟前
软考中级软件设计师 数据结构详细知识点(含真题+练习题,可直接复习)
java·开发语言·数据结构
sthnyph4 分钟前
QT开发:事件循环与处理机制的概念和流程概括性总结
开发语言·qt
北顾笙9807 分钟前
day07-数据结构力扣
数据结构
hanlin0311 分钟前
刷题笔记:力扣第43、67题(字符串计算)
笔记·算法·leetcode
yang_B62113 分钟前
最小二乘法 拟合平面
算法·平面·最小二乘法
放下华子我只抽RuiKe521 分钟前
深度学习全景指南:硬核实战版
人工智能·深度学习·神经网络·算法·机器学习·自然语言处理·数据挖掘
大尚来也34 分钟前
Java 反射:从“动态魔法”到生产实战的避坑指南
开发语言
无心水42 分钟前
Java时间处理封神篇:java.time全解析
java·开发语言·python·架构·localdate·java.time·java时间处理
yangtuoni1 小时前
vscode调试C++程序
c++·ide·vscode
吴秋霖1 小时前
【某音电商】protobuf聊天协议逆向
python·算法·protobuf