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;
    }
};
相关推荐
威迪斯特2 分钟前
Cobra框架:Go语言命令行开发的现代化利器
开发语言·前端·后端·golang·cobra·交互模型·命令行框架
weixin_413063214 分钟前
比较阅读理解opencv 和 LuminanceHDR中 色调映射Drago算法
opencv·算法·计算机视觉·hdr·色调映射
自我意识的多元宇宙4 分钟前
【数据结构】图----图的应用(拓扑排序)
数据结构·算法
Lazionr6 分钟前
双向链表及链表篇总结
数据结构·链表
itzixiao9 分钟前
L1-055 谁是赢家(10 分)[java][python]
java·python·算法
IT利刃出鞘9 分钟前
Java反射--PropertyDescriptor的使用
java·开发语言
ghie909010 分钟前
运用强跟踪无迹卡尔曼滤波来实现捷联惯导的初始对准
算法
㳺三才人子11 分钟前
容器內的 H2 控制台
开发语言·前端·javascript
Evand J11 分钟前
【MATLAB程序】基于RSSI的RFID二维轨迹定位仿真介绍,EKF滤波增加轨迹定位精度。附下载链接
开发语言·matlab·平面·滤波·定位·导航
遇见火星13 分钟前
Firewalld 防火墙实战指南 + TCPWrapper 七层访问控制
开发语言·windows·python