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;
}
相关推荐
SystickInt1 天前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
CS Beginner1 天前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
JAY_LIN——81 天前
指针-数组
c语言·排序算法
yaoh.wang1 天前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
进阶的猪1 天前
STM32 使用HAL库SPI读写FLASH(W25Q128JV)数据 Q&A
c语言·stm32·单片机
LYFlied1 天前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
charlie1145141911 天前
现代C++嵌入式教程:C++98基础特性:从C到C++的演进(1)
c语言·开发语言·c++·笔记·学习·教程
XFF不秃头1 天前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode
菜鸟233号1 天前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
CQ_YM1 天前
Linux管道通信
linux·c语言·管道·ipc·管道通信