LeetCode //C - 541. 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 . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
  • s consists of only lowercase English letters.
  • 1 < = k < = 1 0 4 1 <= k <= 10^4 1<=k<=104

From: LeetCode

Link: 541. Reverse String II


Solution:

Ideas:

1. Helper Function (reverse):

  • This function reverses the characters in the substring of s from index start to end.

2. Main Function (reverseStr):

  • It iterates through the string in segments of 2k.
  • For every 2k segment, the first k characters are reversed. The rest remain unchanged.
  • If there are fewer than k characters left, reverse all of them.
  • If there are between k and 2k characters, reverse the first k and leave the rest unchanged.

3. Edge Cases:

  • When k is greater than the remaining length of the string, it handles it by only reversing up to the string's end.
  • The function is efficient and adheres to the constraints, as the operations are performed in linear time relative to the string length.
Code:
c 复制代码
void reverse(char* s, int start, int end) {
    while (start < end) {
        char temp = s[start];
        s[start] = s[end];
        s[end] = temp;
        start++;
        end--;
    }
}

char* reverseStr(char* s, int k) {
    int len = strlen(s);
    for (int i = 0; i < len; i += 2 * k) {
        // Reverse the first k characters in the current segment
        int end = (i + k - 1 < len) ? i + k - 1 : len - 1;
        reverse(s, i, end);
    }
    return s;
}
相关推荐
带多刺的玫瑰14 分钟前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
en.en..1 小时前
C语言核心解析:#define与typedef本质区别
开发语言·c++·算法
wabs6663 小时前
关于二叉树【429.N叉树的层序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
hetao17338373 小时前
2026-09-08 hetao1733837 的刷题记录
c++·算法
C++ 老炮儿的技术栈4 小时前
MFC CPtrArray的用法
开发语言·数据结构·c++·算法·mfc·c
weixin_446260854 小时前
CABAL:用于追踪同行评审中合谋投标影响的多智能体仿真框架
人工智能·算法·机器学习
不会就选b4 小时前
算法日常・每日刷题--<贪心>6
数据结构·算法·leetcode
青山木4 小时前
Hot 100 --- 跳跃游戏 II
java·数据结构·算法·leetcode·贪心算法
是隼人4 小时前
buuctf-pwn bypwn(ret2shellcode)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
Tisfy4 小时前
LeetCode 3870.统计范围内的逗号:模拟 或 一步计算
数学·算法·leetcode·题解·模拟·遍历