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).

Have you met this question in a real interview?

 
 
Example

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】的更多相关文章

  1. 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 ...

  2. 213. String Compression【LintCode java】

    Description Implement a method to perform basic string compression using the counts of repeated char ...

  3. 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 ...

  4. 606. Construct String from Binary Tree 【easy】

    606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...

  5. 344. Reverse String【easy】

    344. Reverse String[easy] Write a function that takes a string as input and returns the string rever ...

  6. 189. Rotate Array【easy】

    189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = ...

  7. 551. Student Attendance Record I【easy】

    551. Student Attendance Record I[easy] You are given a string representing an attendance record for ...

  8. 383. Ransom Note【easy】

    383. Ransom Note[easy] Given an arbitrary ransom note string and another string containing letters f ...

  9. 657. Judge Route Circle【easy】

    657. Judge Route Circle[easy] Initially, there is a Robot at position (0, 0). Given a sequence of it ...

随机推荐

  1. Oracle数据库中的所有用户名

    select * from dba_users; 查看数据库里面所有用户,前提是你是有dba权限的帐号,如sys,systemselect * from all_users;  查看你能管理的所有用户 ...

  2. vim的批量列编辑

    使用快捷键:control+v进入状态“VISUALBLOCK”,然后使用方向键向下选择,选择多行,向右选择,选择多列,使用快捷键d删除所选. 再次进入VISUAL BLOCK状态,选择多行多列, 使 ...

  3. iOS:quartz2D绘图 (动画)

    quartz2D可以用来绘制自己需要的图形,它们绘制出来的是一个静态的图形,那么如何绘制一个动态的图形呢?动态的图形就是动画,所谓动画,其实就是很多张图片在短时间内不停的切换所产生的一种视觉效果.qu ...

  4. xss bypass

    重要的4个规则: 1 &符号不应该出现在HTML的大部分节点中. 2 尖括号<>是不应该出现在标签内的,除非为引号引用. 3 在text节点里面,<左尖括号有很大的危害. 4 ...

  5. ArcGIS Server 10中的切图/缓存机制深入【转】

    http://blog.newnaw.com/?p=789 两年前我写过一篇关于ArcGIS地图切图/缓存原理的文章,<ArcGIS Server的切图原理深入>,里面以tiling sc ...

  6. 批处理命令中set定义的两种变量介绍 计算机基础知识

    摘自: http://www.amhl.net/wenzhang/DianNaoChangShi/20101201/127422.html 所谓的自定义变量,就是由我们来给它赋予值的变量. ①赋值变量 ...

  7. Android-ImageView的属性android:scaleType作用

    在网上查了好多资料,大致都雷同,大家都是互相抄袭的,看着很费劲,不好理解,自己总结一下,留着需要看的话来查找. 代码中的例子如下: <ImageView android:id="@+i ...

  8. 使用airdrop进行文件共享

    使用airdrop进行文件共享 学习了: https://support.apple.com/zh-cn/HT203106 https://zh.wikihow.com/%E5%9C%A8Mac%E4 ...

  9. 转: iOS崩溃堆栈符号表使用与用途

    转:http://bugly.qq.com/blog/?p=119 iOS崩溃堆栈符号化,定位问题分分钟搞定! 2015.3.16 腾讯Bugly 微信分享   最近一段时间,在跟开发者沟通过程中,萝 ...

  10. okhttp-OkGo的文件下载模块

    OkDownload主要功能 结合OkGo的request进行网络请求,支持与OkGo保持相同的配置方法和传参方式 支持断点下载,支持突然断网,强杀进程后,继续断点下载 每个下载任务具有无状态.下载. ...