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;
    }
};
相关推荐
爱睡懒觉的焦糖玛奇朵16 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具使用说明】
人工智能·python·深度学习·学习·算法·yolo·音视频
Runawayliquor16 小时前
opbase:CANN 所有算子的公共地基
大数据·数据库·人工智能·算法
徐安安ye16 小时前
FlashAttention 为什么对序列长度这么“敏感”?
人工智能·算法
潜创微科技17 小时前
IT6520:USB‑C 转 MIPI 芯片方案 4K@120Hz 高清显示
c语言·开发语言
言之。17 小时前
【Python】免费的中文 AI 配音方案
开发语言·人工智能·python
kyle~17 小时前
机器视觉---熔池相机(穿透强光的视觉感知)
c++·数码相机·计算机视觉·机器人·焊接机器人
宏笋18 小时前
C++ Coroutines(协程) 详解
c++
天天进步201518 小时前
Python全栈项目:从零手操一个高性能 API 网关
开发语言·python
Java面试题总结18 小时前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
王老师青少年编程18 小时前
csp信奥赛C++高频考点专项训练之前缀和&差分 --【一维前缀和】:求区间和
c++·前缀和·csp·高频考点·信奥赛·求和区间和