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;
}
相关推荐
逆小舟2 小时前
【C/C++】指针
c语言·c++·笔记·学习
earthzhang20212 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
迎風吹頭髮2 小时前
UNIX下C语言编程与实践63-UNIX 并发 Socket 编程:非阻塞套接字与轮询模型
java·c语言·unix
奔跑吧邓邓子3 小时前
【C语言实战(6)】解锁C语言循环密码:for循环实战探秘
c语言·实战·for循环
GilgameshJSS4 小时前
STM32H743-ARM例程15-RTC
c语言·arm开发·stm32·实时音视频
pu_taoc4 小时前
深入剖析:基于epoll与主从Reactor模型的高性能服务器设计与实现
服务器·c语言·c++·vscode
小欣加油5 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗5 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗5 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
Mr.Ja6 小时前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器