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;
}
相关推荐
进击的_鹏16 分钟前
数据结构之链表(1),单链表
c语言·数据结构·链表
码农小苏241 小时前
力扣刷题--476. 数字的补数【简单】
数据结构·算法·leetcode
九离十2 小时前
初识C语言(四)
c语言·开发语言
nuo5342022 小时前
数学期望专题
c语言·c++·算法·概率论
霍金的微笑2 小时前
LeetCode
算法·leetcode·职场和发展
冰淇淋加点糖3 小时前
C语言基础之数组
c语言·数据结构·算法
长天一色3 小时前
C语言日志类库 zlog 使用指南(第四章 Syslog模式)
linux·c语言·openeuler
Ddddddd_1584 小时前
C++ | Leetcode C++题解之第446题等差数列划分II-子序列
c++·leetcode·题解
Beautyxxi6 小时前
9.29 LeetCode 3304、3300、3301
算法·leetcode·职场和发展