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;
}
相关推荐
李白同学24 分钟前
【C语言】结构体内存对齐问题
c语言·开发语言
楼台的春风2 小时前
【MCU驱动开发概述】
c语言·驱动开发·单片机·嵌入式硬件·mcu·自动驾驶·嵌入式
大数据追光猿2 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!2 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉2 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生2 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴2 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing2 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财2 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程2 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛