1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

这道题让我们压缩给定的字符串,压缩方法是对于重复的字符,用数字来表示重复的个数,这种压缩方法对于有很多重复字符具有很高的压缩效率,但是对于不重复的字符串,压缩后的表示方法反而比不压缩占空间大。所以我们首先要先来计算下压缩后的字符串的长度,和原字符串长度比较,如果大的话,则直接返回原字符串,如果小的话,则我们就开始压缩。那么我们需要建立一个新字符串来保存压缩后的字符串,这里书中特别提到了用字符串的相加的方法是很没有效率的,下面英文部分摘自Cracking the coding interview 5th edition的第72页:

Imagine you were concatenating a list of strings, as shown below. What would the running time of this code be? For simplicity, assume that the strings are all the same length (call this x) and that there are n strings.

public String joinWords(String[] words) {
String sentence = "";
for (String w : words) {
sentence = sentence + w;
}
return sentence;
}

On each concatenation, a new copy of the string is created, and the two strings are copied over, character by character. The first iteration requires us to copy x characters. The second iteration requires copying 2x characters.The third iteration requires 3x, and
so on.The total time therefore is 0(x + 2x + ... + nx). This reduces to 0(xn2). (Why isn't it 0(xnn)? Because 1 + 2 + ... + nequals n(n+l)/2,orO(n2).)

根据上面所说,字符串的拼接余姚拷贝拼接的两个字符串,当字符串长度很长的时候,这种方法非常没有效率,所以我们要避免使用拼接的方法。那么我们的替代方法是先声明好一个定长的字符串,然后给每个位置赋值。压缩后的字符串长度我们开始计算过了,所以只需要给每个位置赋值即可,跟之前那道1.4 Replace Spaces 替换空格有些相似,参见代码如下:

class Solution {
public:
string compress(string s) {
int newLen = countCompression(s);
if (newLen >= s.size()) return s;string res(newLen, ' ');
char c = s[];
int cnt = , idx = ;
for (int i = ; i < s.size(); ++i) {
if (s[i] == c) ++cnt;
else {
res[idx++] = c;
for (auto a : to_string(cnt)) res[idx++] = a;
c = s[i];
cnt = ;
}
}
res[idx++] = c;
for (auto a : to_string(cnt)) res[idx++] = a;
return res;
}
int countCompression(string s) {
if (s.empty()) return ;
int res = , cnt = ;
char c = s[];
for (int i = ; i < s.size(); ++i) {
if (s[i] == c) ++cnt;
else {
c = s[i];
res += + to_string(cnt).size();
cnt = ;
}
}
res += + to_string(cnt).size();
return res;
}
};

[CareerCup] 1.5 Compress String 压缩字符串的更多相关文章

  1. [CareerCup] 1.2 Reverse String 翻转字符串

    1.2 Implement a function void reverse(char *str) in C or C++ which reverses a null-terminated string ...

  2. [CareerCup] 18.8 Search String 搜索字符串

    18.8 Given a string s and an array of smaller strings T, design a method to search s for each small ...

  3. [LeetCode] Design Compressed String Iterator 设计压缩字符串的迭代器

    Design and implement a data structure for a compressed string iterator. It should support the follow ...

  4. Java 压缩字符串

    1.引言 最近在做项目中,平台提供一个http服务给其他系统调用,然后我接收到其他系统的json格式的报文后去解析,然后用拿到的数据去调用corba服务,我再把corba的返回值封装完成json字符串 ...

  5. String压缩 解压缩

    数据传输时,有时需要将数据压缩和解压缩,本例使用GZIPOutputStream/GZIPInputStream实现. 1.使用ISO-8859-1作为中介编码,可以保证准确还原数据 2.字符编码确定 ...

  6. Java压缩字符串的方法收集

    说明: 1.一般来说要实现压缩,那么返回方式一般是用byte[]数组. 2.研究发现byte[]数组在转成可读的String时,大小会还原回原来的. 3.如果采用压缩之后不可读的String时,互相转 ...

  7. NYOJ 1067 Compress String(区间dp)

    Compress String 时间限制:2000 ms  |  内存限制:65535 KB 难度:3 描写叙述 One day,a beautiful girl ask LYH to help he ...

  8. C#压缩字符串

    在论坛上看到一个压缩字符串的问题,特此记录以备后用! static string GetStringR(string inputStr) { return Regex.Replace(inputStr ...

  9. Java压缩字符串工具类

    StringCompressUtils.java package javax.utils; import java.io.ByteArrayInputStream; import java.io.By ...

随机推荐

  1. 深入理解java虚拟机(6)---内存模型与线程 & Volatile

    其实关于线程的使用,之前已经写过博客讲解过这部分的内容: http://www.cnblogs.com/deman/category/621531.html JVM里面关于多线程的部分,主要是多线程是 ...

  2. WebApi 使用PUT和DELETE时报405的问题

    最近两天写了个项目,里面有一个接口是用谓词delete接收请求. 本地完全没问题,但是当发布到服务器上之后(IIS7.5),就报出 405.0 - Method Not Allowed 很明显是配置问 ...

  3. 图解 SQL 各种连接查询之间的区别

    转载自:http://blog.csdn.net/xuanjiewu/article/details/50636465 对于SQL的Join,在学习起来可能是比较乱的.我们知道,SQL的Join语法有 ...

  4. java微信接口之五—消息分组群发

    一.微信消息分组群发接口简介 1.请求:该请求是使用post提交地址为: https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_t ...

  5. 第二章 Mysql 数据类型简介--(整数类型、浮点数类型和定点数类型,日期与时间类型,字符串类型,二进制类型)

    第一节:整数类型.浮点数类型和定点数类型 1,整数类型 2,浮点数类型和定点数类型 M 表示:数据的总长度(不包括小数点):D 表示:小数位:例如 decimal(5,2) 123.45存入数据的时候 ...

  6. stm32时钟分析

    转载自http://blog.chinaunix.net/uid-21658993-id-3129667.html   在STM32中,有五个时钟源,为HSI.HSE.LSI.LSE.PLL. 其实是 ...

  7. 同时屏蔽ios和android下点击元素时出现的阴影

    在ios4+和android2+系统,当手指触摸屏幕a标签链接或按钮时,会产生不同的效果,对于ios点击元素的时候,就会出现一个半透明的灰色背景:对于android则出现红色的边框.对这2个系统自带的 ...

  8. pyhon之Tkinter实例化学习

    Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口,位Python的内置模块,直接import tkinter即可使用. 作为实践, 用Tkinter ...

  9. Laxcus大数据管理系统2.0(5)- 第二章 数据组织

    第二章 数据组织 在数据的组织结构设计上,Laxcus严格遵循数据和数据描述分离的原则,这个理念与关系数据库完全一致.在此基础上,为了保证大规模数据存取和计算的需要,我们设计了大量新的数据处理技术.同 ...

  10. 每日学习心得:UEditor样式被过滤无法显示问题

    前言: 上周开发中有用到开源的富文本编辑器UEditor,在使用的过程中遇到了样式被过滤无法显示问题,经过一番折腾终解决,此外,还有一些关于获取前台界面元素的一些总结. 1. UEditor样式被过滤 ...