C语言 | Leetcode C语言题解之第443题压缩字符串

题目:

题解:

cpp 复制代码
void swap(char *a, char *b) {
    char t = *a;
    *a = *b, *b = t;
}

void reverse(char *a, char *b) {
    while (a < b) {
        swap(a++, --b);
    }
}

int compress(char *chars, int charsSize) {
    int write = 0, left = 0;
    for (int read = 0; read < charsSize; read++) {
        if (read == charsSize - 1 || chars[read] != chars[read + 1]) {
            chars[write++] = chars[read];
            int num = read - left + 1;
            if (num > 1) {
                int anchor = write;
                while (num > 0) {
                    chars[write++] = num % 10 + '0';
                    num /= 10;
                }
                reverse(&chars[anchor], &chars[write]);
            }
            left = read + 1;
        }
    }
    return write;
}
相关推荐
GilgameshJSS11 小时前
STM32H743-ARM例程38-UART-IAP
c语言·arm开发·stm32·单片机·嵌入式硬件
sin_hielo12 小时前
leetcode 1611
算法·leetcode
来荔枝一大筐13 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
apocelipes13 小时前
POSIX兼容系统上read和write系统调用的行为总结
linux·c语言·c++·python·golang·linux编程
是苏浙14 小时前
零基础入门C语言之C语言实现数据结构之顺序表应用
c语言·数据结构·算法
小白程序员成长日记14 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白14 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
雾岛听蓝15 小时前
算法复杂度解析:时间与空间的衡量
c语言·数据结构·经验分享·笔记
小白程序员成长日记15 小时前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
Nebula_g15 小时前
C语言应用实例:学生管理系统1(指针、结构体综合应用,动态内存分配)
c语言·开发语言·学习·算法·基础