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;
}
相关推荐
zcg19425 分钟前
图像分割——常用数据和算法
算法
子午7 分钟前
基于YOLO的车牌识别检测~Python+YOLOV8算法+车牌定位+车牌检测+深度学习
python·算法·yolo
heimeiyingwang14 分钟前
【架构实战】分布式ID生成:雪花算法与业务ID设计
分布式·算法·架构
学会去珍惜14 分钟前
C++如何与C语言混合编程_在C++项目中调用C库函数的extern “C“方法
c语言·c++·混合编程·extern
代码中介商19 分钟前
排序算法完全指南(一):冒泡排序深度详解
算法·排序算法
灰灰勇闯IT22 分钟前
MindSpore 和 CANN 是什么关系——用一个厨房讲明白
人工智能·深度学习·算法·cann
阳明山水23 分钟前
模型迭代实战:如何将准确率从75%提升到89%
数据结构·人工智能·算法·机器学习·微信·微信公众平台·微信开放平台
呃呃本35 分钟前
算法题(贪心算法)
算法·贪心算法
听你说3236 分钟前
不迷路、不重扫、不遗漏:库萨科技无人清扫车以空间智能领跑无人环卫赛道
人工智能·科技·算法·机器人
吃好睡好便好40 分钟前
在Matlab中绘制三维直方图
开发语言·学习·算法·matlab·信息可视化