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;
}
相关推荐
陳麦冬20 分钟前
深入理解指针(二)
c语言·学习
爱coding的橙子2 小时前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光2 小时前
leetcode sql50题
算法·leetcode·职场和发展
pay顿2 小时前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
岁忧2 小时前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy2 小时前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·
dying_man2 小时前
LeetCode--18.四数之和
算法·leetcode
景彡先生4 小时前
C++中的变量
c语言
客卿1237 小时前
力扣100-移动0
算法·leetcode·职场和发展
緈福的街口13 小时前
【leetcode】347. 前k个高频元素
算法·leetcode·职场和发展