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;
}
相关推荐
qq_513970441 小时前
力扣 hot100 Day56
算法·leetcode
爱装代码的小瓶子3 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男4 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao4 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
快乐飒男5 小时前
哈希表(c语言)
c语言·哈希算法·散列表
aramae6 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
大锦终6 小时前
【算法】前缀和经典例题
算法·leetcode
cccc来财7 小时前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode
程序员编程指南8 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
恣艺8 小时前
LeetCode 854:相似度为 K 的字符串
android·算法·leetcode