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;
}
相关推荐
老洋葱Mr_Onion17 分钟前
【C++】CSP-J初赛模拟卷七错题整理(作者自用)
c++·算法·深度优先
Nil20831 分钟前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
土星云SaturnCloud40 分钟前
Real-ESRGAN超分辨率算法原理与边缘侧部署实践
服务器·算法·ai·边缘计算·real-esrgan
cz071043 分钟前
hot100_搜索二维矩阵 II
算法·leetcode
疯狂打码的少年1 小时前
【数据结构】板块总结 + 下期预告(数据库技术)
数据结构·笔记·算法
郝学胜_神的一滴1 小时前
Effective Python 条款 2:遵循 PEP 8 编码风格,写出高质量 Python 代码
python·算法
郝学胜-神的一滴1 小时前
Effective Python 条款 1:确认你正在使用的 Python 版本
开发语言·数据结构·python·程序人生·算法
sel_92 小时前
【多轮对话论文导读(二)】多轮对话与LLM Agent论文阅读:长期记忆、多轮评估与Agent训练
人工智能·深度学习·算法·语言模型·自然语言处理
一木 之林2 小时前
五、C++新特性、关键字与编译原理
java·jvm·算法
昌原的儿子LEO3 小时前
Linux进程知识点总结
linux·服务器·c语言·数据库