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. 【iOS开发】canOpenURL: failed for URL

    控制台输出 如图是在我启动一个 Xcode 7 + iOS 9 的 App 之后,控制台的输出. 这在 Xcode 6.4 + iOS 8 时,是不会有的情况,原因是[为了强制增强数据访问安全, iO ...

  2. 深入浅出RxJava就这一篇就够了

    前言: 第一次接触RxJava是在前不久,一个新Android项目的启动,在评估时选择了RxJava.RxJava是一个基于事件订阅的异步执行的一个类库.听起来有点复杂,其实是要你使用过一次,就会大概 ...

  3. ECMAScript 6(ES6)常用语法

     一:Let和const (1)Let定义块级作用域的变量,var定义的变量会提升.Let不会提升. 如下.var可以先用,打印是undefined但是let在定义之前是不能用的. 会报错Uncaug ...

  4. 12.线程通信CyclicBarrier

    CountDownLatch 监听某个线程的初始化,等待初始化执行完毕后,通知主线程工作.延迟.阻塞的是主线程,在单个线程中. CyclicBarrier 针对多个线程.线程池,多个线程初始化准备之后 ...

  5. 15.同步类容器Vector

    同步类容器1 1.线程都是安全的. 2.在某些场景下需要加锁来保护“复合操作” a.迭代:反复去访问元素.遍历完容器所有的元素 b.跳转:根据下标制定去访问查找元素 c.条件运算 3.复合操作在多线程 ...

  6. CMakeFile命令之file

    file:文件操作命令. file(WRITE filename "message towrite"... ) WRITE 将一则信息写入文件’filename’中,如果该文件存在 ...

  7. 对Emlog 6.0 Beta的完整代码审计过程

    Emlog 6.0 beta版本,这可能是最后一篇关于PHP语言CMS的代码审计文章,此次将详细记录完整的审计过程. 文章基本上完整记录小东的对此CMS审计过程,或许显得繁琐,但代码审计的过程就是这样 ...

  8. SQL中inner join,outer join和cross join的区别

    使用join连表,缺陷的情况下是inner join,开发中使用的left join和right join属于outer join,outer join还包括full join 现有两张表,Table ...

  9. hdu-Coins

    http://acm.hdu.edu.cn/showproblem.php?pid=2844 Problem Description Whuacmers use coins.They have coi ...

  10. Spring Boot + Spring Data + Elasticsearch实例

    Spring Boot + Spring Data + Elasticsearch实例 学习了:https://blog.csdn.net/huangshulang1234/article/detai ...