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;
}
相关推荐
坚持不懈的大白22 分钟前
Leetcode学习笔记
笔记·学习·leetcode
Tisfy2 小时前
LeetCode 3047.求交集区域内的最大正方形面积:2层循环暴力枚举
算法·leetcode·题解·模拟·枚举·几何
Frank Castle2 小时前
【C语言】详解C语言字节打包:运算符优先级、按位或与字节序那些坑
c语言·开发语言
ltqshs3 小时前
vscode离线插件下载-vscode编译嵌入式C语言配置
c语言·ide·vscode
栈与堆3 小时前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
鹿角片ljp3 小时前
力扣7.整数反转-从基础到边界条件
算法·leetcode·职场和发展
java修仙传3 小时前
力扣hot100:前K个高频元素
算法·leetcode·职场和发展
小乔的编程内容分享站4 小时前
C语言指针相关笔记
c语言·笔记
爱编码的傅同学6 小时前
【今日算法】Leetcode 581.最短无序连续子数组 和 42.接雨水
数据结构·算法·leetcode