213. String Compression【easy】
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.
You can assume the string has only upper and lower case letters (a-z).
str=aabcccccaaa
return a2b1c5a3
str=aabbcc
return aabbcc
str=aaaa
return a4
解法一:
public class Solution {
/**
* @param str a string
* @return a compressed string
*/
public String compress(String str) {
// Corner case
if (str == null) {
return null;
} else if (str.length() <= 2) {
return str;
} StringBuilder sb = new StringBuilder();
char temp = str.charAt(0);
int count = 1; for (int i = 1; i < str.length(); i++) {
// If same char continues, then add the count
if (str.charAt(i) == temp) {
count++;
} else {
// Encounter different char, set temp to the char and count to 1
sb.append(temp);
sb.append(count);
temp = str.charAt(i);
count = 1;
}
} // Do not forget the last char and the count!!!
sb.append(temp).append(count); // Compare the result of original str with the new stringbuilder
if (sb.length() >= str.length()) {
return str;
} else {
return sb.toString();
}
}
}
Here we use StringBuilder to create a new String, instead of String concatenation. That’s because for String concatenation operation, it’ll build a new string for every operation.
The basic algorithm is:
1、Create stringbuilder and initialize the first temp char, with count = 1
2、Go through the string char by char
(1)If char(i) equals to temp, continue and add count
(2)If not, add the temp and count to stringbuilder, reset the temp to be char(i) and count to be 1
3、Go out of the loop and add the last char and count for it
4、Compare the stringbuilder with initial str
Note: After go through the for loop, the temp is equals the last - 1 char, so we need to add the last char with its count.
Time complexity: O(n)
Space complexity: O(n)
参考@Steven Wu 的代码
https://codebysteven.wordpress.com/2016/03/14/lintcode-string-compression/
解法二:
public class Solution {
/*
* @param str: a string
* @return: a compressed string
*/
public String compress(String str) {
if (str == null || str.length() < 3) {
return str;
}
StringBuilder sb = new StringBuilder();
Map<Character, Integer> map = new HashMap<>();
char pre = str.charAt(0);
map.put(pre, 1);
for (int i = 1; i < str.length(); i++) {
char cur = str.charAt(i);
if (cur == pre) {
map.put(pre, map.get(pre)+1);
} else {
sb.append(pre);
sb.append(map.get(pre));
map.put(pre, 0);
map.put(cur, 1);
pre = cur;
}
}
sb.append(pre);
sb.append(map.get(pre));
String res = sb.toString();
return res.length() < str.length() ? res : str;
}
}
参考@linspiration 的代码
https://segmentfault.com/a/1190000012634492
213. String Compression【easy】的更多相关文章
- 557. Reverse Words in a String III【easy】
557. Reverse Words in a String III[easy] Given a string, you need to reverse the order of characters ...
- 213. String Compression【LintCode java】
Description Implement a method to perform basic string compression using the counts of repeated char ...
- 345. Reverse Vowels of a String【easy】
345. Reverse Vowels of a String[easy] Write a function that takes a string as input and reverse only ...
- 606. Construct String from Binary Tree 【easy】
606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...
- 344. Reverse String【easy】
344. Reverse String[easy] Write a function that takes a string as input and returns the string rever ...
- 189. Rotate Array【easy】
189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = ...
- 551. Student Attendance Record I【easy】
551. Student Attendance Record I[easy] You are given a string representing an attendance record for ...
- 383. Ransom Note【easy】
383. Ransom Note[easy] Given an arbitrary ransom note string and another string containing letters f ...
- 657. Judge Route Circle【easy】
657. Judge Route Circle[easy] Initially, there is a Robot at position (0, 0). Given a sequence of it ...
随机推荐
- Android(Fragment和Activity之间通信)
Fragment的使用可以让我们的应用更灵活的适配各种型号的安卓设备,但是对于Fragment和Activity之间的通信,很多朋友应该比较陌生,下面我们就通过一个实例来看一看如何实现. 一.Acti ...
- vue项目中使用地图组件
一.引入高德地图 一般用使用vue-cli webpack最简单粗暴的引入地图api的方法就是,在入口index.html的头部直接引入,记得一定要带上key,如果没有的话去高德地图api的官网申请一 ...
- 在Oracle 11.2.0.1.0下dbms_stats.gather_table_stats收集直方图不准
SQL> select * from v$version; BANNER ------------------------------------------------------------ ...
- thinkphp5.0 中使用第三方无命名空间的类库
ThinkPHP5建议所有的扩展类库都使用命名空间定义,如果你的类库没有使用命名空间,则不支持自动加载,必须使用Loader::import方法先导入文件后才能使用. 首先要在文件头部使用loader ...
- Lateral View使用指南
https://blog.csdn.net/sunnyyoona/article/details/62894761 select sum(pitem) from (select map_values( ...
- windows下mysql中文乱码, 配置解决方法
内容源自:windows下mysql中文乱码, 配置解决方法 解决方法:打开mysql安装目录,打开my.ini文件(如果只有my-default.ini文件,先将其改名为my.ini!!!) 修改内 ...
- 与Xamarin.Forms跨平台的用户界面
Xamarin.Forms 与Xamarin.Forms跨平台的用户界面 Xamarin的. 形式是一个跨平台的UI工具包,它允许开发人员 轻松地创建本地用户界面布局,可以共享 在Android,iO ...
- MyEclipse 集成 Gradle开发环境
一.上Grandle官网下载Gradle,地址:http://www.gradle.org/downloads 如果只是运行只下载gradle-2.6-bin.zip 就可以了,如果为了扩展开发的话就 ...
- hdu1800Flying to the Mars (字典树)
Problem Description In the year 8888, the Earth is ruled by the PPF Empire . As the population growi ...
- 利用jspx解决jsp后缀被限制拿shell
有些struts2的站在web.xml里面设置url是jsp的格式就自动跳转主页的action,转换jsp后缀大小写还不解析.查了查有Tomcat默认jspx可以解析.看了看jspx的手册,那就好说了 ...