CTCI系列--1.5 字符串压缩(C语言)
来源:互联网 发布:淘宝买家信用查询工具 编辑:程序博客网 时间:2024/04/28 12:53
题目:Implement a method to perform basic string compression using the counts of repeated characters. For example,the string aabcccccaaa would become a2b1c5a3.If the “compressed” string would not become smaller than the original string,your method should return the original string.
实现一个方法,使用统计重复字符的方式完成基础字符串压缩。举个例子,字符串aabcccccaaa将被压缩为a2b1c5a3。如果压缩后的字符串不比原始字符串小,你的方法需要返回原始字符串。
解题思路
- 获取字符串字符个数,申请字符个数*2的空间作为压缩字符串存储空间
- 遍历字符串,先取字符串第一个字符,往后比较是否与第一个字符一致,若一致则字符统计计数加1;若不一致则跳到下一步
- 将目前比较的字符以及统计计数拼接到压缩字符串中,将比较字符替换为当前位置字符,统计计数置1,跳转到下一步;若遍历到字符串末尾则到下一步
- 比较压缩后字符串与原始字符串的长度,若压缩后比压缩前短,则返回压缩后的字符串;否则返回原始字符串
代码实现
#include <stdio.h>#include <string.h>#include <stdlib.h>void test(char *buf,char **prnt){ int res_len = 0, ori_len = 0; char *res = NULL; int i; char tmp_c = 0; int tmp_count=0; char tmpbuf[10]; ori_len = strlen(buf); res = malloc(ori_len * 2); if (res == NULL) return; memset(res, 0, ori_len * 2); tmp_c = buf[0]; for (i = 0; i < ori_len+1; i++) { if (tmp_c == buf[i]) { tmp_count++; } else { memset(tmpbuf, 0, sizeof(tmpbuf)); sprintf(tmpbuf, "%c%d", tmp_c, tmp_count); strcat(res, tmpbuf); tmp_c = buf[i]; tmp_count = 1; } } res_len = strlen(res); if (res_len < ori_len) { *prnt = res; } else { *prnt = buf; }}int main(void){ char buf[100]; char *res = NULL; memset(buf, 0, sizeof(buf)); sprintf(buf, "aabcccccaaa"); printf("original string : %s\n", buf); test(buf,&res); printf("After compression : %s\n", res); getchar(); return 0;}
运行结果
文章转载自我的非鱼物语
本文固定链接为:http://linuxue.com/archives/22
0 0
- CTCI系列--1.5 字符串压缩(C语言)
- CTCI系列--1.2 字符串翻转(C语言)
- 《CTCI》1.5 字符串“压缩”
- CTCI系列--1.1 判断一个字符串中的字符是否唯一(C语言)
- CTCI系列--1.3 判断两个字符串是否互为变换(C语言)
- CTCI系列--1.4 字符替换(C语言)
- c语言字符串处理-----压缩字符串
- [google面试CTCI] 1-2 逆转c风格字符串
- 字符串压缩——C语言
- C语言系列(三)字符串处理函数
- C语言系列(三)字符串处理函数
- 华为2014年机试题【字符串压缩】-【C语言/C++】
- C语言基础系列--字符串有关内容
- C语言系列之C语言如何返回字符串数组
- 字符串(C语言)
- 模拟实现C语言字符串系列和memory系列库函数
- C字符串压缩算法
- 文件压缩(平台Linux & 语言C++)
- CTCI系列--1.4 字符替换(C语言)
- 蓝牙签到系统 入公司自动打卡
- Android6.0 otg插入U盘 流程
- 【Deep Learning】Review:Rich feature hierarchies for accurate object detection and semantic segmentati
- 销售到出仓所经历的表
- CTCI系列--1.5 字符串压缩(C语言)
- Android Intent跳转活动
- 《iOS Human Interface Guidelines》——Accessing User Data
- 2012年第三届蓝桥杯C/C++程序设计本科B组省赛 放棋子(代码填空)
- 卸载微软新体验2010
- bci 综述文章
- POJ 2752 Seek the Name, Seek the Fame KMP Next[]
- 【Deep Learning】Review:Faster R-CNN- TowardsReal-Time Object Detection with Region Proposal Networks
- linux 驱动之 dts