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 ...
随机推荐
- WinCE5.0开发环境的建立
目前WinCE5.0的开发工具主要有以下几种:Platform Builder5.0.EVC4.0+SP4.Visual Studio2005.其中Platform Builder主要用于定制WinC ...
- 小程序把图片转换成base64
1.首先需要到upng.js,然后upng.js需要pako.js,先一并下载了 2.然后就可以直接用了,具体代码如下: <!--pages/base/base.wxml--> <c ...
- @MySQL为表字段添加索引
删除索引~ DROP INDEX `idx_dict_type` ON `article` 1.添加PRIMARY KEY(主键索引): ALTER TABLE `table_name` ADD PR ...
- 用BETTERCAP和RASPBERRY PI ZERO W制作迷你WiFi干扰器
我并不是一个特别勤快的人,几天前我终于开始将我几周以来的一些想法付诸于实践,即使用Raspberry Pi Zero W制作一个可随身携带的迷你WiFi干扰器.有了它,我就可以随时随地的收集附近无线接 ...
- SecureCRT配置文件保存和导入
每次重装系统,都要重新配置SecureCRT,为了减少重复工作.直接在SecureCRT软件中找到:选项---全局选项---常规---配置文件夹下面路径:C:\Users\Administrator\ ...
- (转)Android技术积累:图片缓存管理
如果每次加载同一张图片都要从网络获取,那代价实在太大了.所以同一张图片只要从网络获取一次就够了,然后在本地缓存起来,之后加载同一张图片时就从缓存中加载就可以了.从内存缓存读取图片是最快的,但是因为内存 ...
- Intellij IDEA中使用log4j日志
一.在pom.xml中添加依赖 <dependency> <groupId>log4j</groupId> <artifactId>log4j</ ...
- Android-自己定义PopupWindow
Android-自己定义PopupWindow 2014年5月12日 PopupWindow在应用中应该是随处可见的,非经常常使用到,比方在旧版本号的微信其中就用到下拉的PopupWindow.那是自 ...
- 解决tomcat提交的数据乱码的问题
有时,开发过程中会遇到前端传入“中文”并返回时,会出现乱码!主要是因为前端通过tomcat7提交的数据就出现了乱码的问题,也就说根源在于tomcat7. 有2中方案解决该问题: (1)使用tomcat ...
- Core Data 删除某条指定记录的数据
一:操作流程 先查询得到某条要删除的数据 然后删除某记录 二:演示代码 //删除 - (void)deleteThePersonData { NSFetchRequest *fetchRequest ...