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;
    }
};
相关推荐
像风一样自由2020几秒前
Rust Tokio vs Go net/http:云原生与嵌入式生态选型指南
开发语言·golang·rust
DuHz2 分钟前
C程序中的数组与指针共生关系
linux·c语言·开发语言·嵌入式硬件·算法
而后笑面对3 分钟前
力扣2025.10.19每日一题
算法·leetcode·职场和发展
我星期八休息6 分钟前
C++智能指针全面解析:原理、使用场景与最佳实践
java·大数据·开发语言·jvm·c++·人工智能·python
大猫会长10 分钟前
docker安装php+apache
java·开发语言
·白小白21 分钟前
力扣(LeetCode) ——11.盛水最多的容器(C++)
c++·算法·leetcode
道之极万物灭24 分钟前
Go小工具合集
开发语言·后端·golang
梵得儿SHI35 分钟前
Java 反射机制深度剖析:性能与安全性的那些坑
java·开发语言·安全·反射·动态代理·性能·反射机制
fsnine40 分钟前
Python图形化界面——pyqt5教程
开发语言·python·qt
嵌入式-老费1 小时前
Easyx图形库应用(和lua结合使用)
开发语言·lua