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;
}
相关推荐
Galerkin码农选手1 分钟前
awq_marlin和gptq_marlin量化算法简要介绍
算法
buhuizhiyuci1 分钟前
【算法篇】动态规划——斐波那契数列模型
算法·动态规划
棱镜研途3 分钟前
学习笔记丨模式识别与机器学习5大核心赛道解析(IC-IPPR 2026)
人工智能·神经网络·算法·机器学习·模式识别·学术会议·智能计算
SuperHeroWu713 分钟前
【算法】逻辑回归虽然名字中有“回归“,但通常用于二分类任务。如何理解学习?
算法·回归·逻辑回归·二分类任务
gCode Teacher 格码致知17 分钟前
Python教学:十六进制编码的显示方法-由Deepseek产生
开发语言·python·算法
2301_7779983417 分钟前
基础IO:IO操作&&重定向
linux·c语言
05候补工程师17 分钟前
【408数据结构】核心考点:图(Graph)精炼笔记与算法直觉
数据结构·经验分享·笔记·考研·算法·图论
靠沿18 分钟前
【动态规划算法】专题三——简单多状态dp问题
算法·动态规划
社交怪人19 分钟前
【收费】信息学奥赛一本通C语言解法(题号2055)
c语言
吃好睡好便好20 分钟前
矩阵秩的计算
人工智能·学习·线性代数·算法·机器学习·matlab·矩阵