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;
}
相关推荐
二进制person4 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6664 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way4 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
码农不惑5 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
.30-06Springfield5 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
凌肖战6 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
BreezeJuvenile7 小时前
数据结构与算法分析课设:一元多项式求值
c语言·课程设计·数据结构与算法分析·一元多项式计算
weixin_478689767 小时前
十大排序算法汇总
java·算法·排序算法
luofeiju7 小时前
使用LU分解求解线性方程组
线性代数·算法
SKYDROID云卓小助手8 小时前
无人设备遥控器之自动调整编码技术篇
人工智能·嵌入式硬件·算法·自动化·信号处理