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. HTML 标签的 enctype 属性

    定义和用法 enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码. 默认地,表单数据会编码为 "application/x-www-form-urlencoded" ...

  2. CCControlExtension/CCControlButton

    #ifndef __CCCONTROL_BUTTON_H__ #define __CCCONTROL_BUTTON_H__ #include "CCControl.h" #incl ...

  3. Java笔记19:Java匿名内部类

    匿名内部类也就是没有名字的内部类.正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写.但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口 例1:不使用匿名内部类来实现抽象方 ...

  4. db2 v9.5迁移至v10.5,及遇重名节点数据库无法创建db的解决办法

    同系统同版本可以使用备份恢复,本文前提是不同系统不同版本,使用db2move命令. 1.db2move db db_name export 此处注意,先建个目录放文件,因为文件比较多,如果上来直接ex ...

  5. C语言面试问题

    内容源自:C语言面试题大汇总 P.S.只摘取了自己觉得可能会被问到的以及不会的. static有什么用途?(请至少说明两种) 1.限制变量的作用域2.设置变量的存储域 引用与指针有什么区别? 1) 引 ...

  6. (转)IntelliJ IDEA下的使用git

    1.git简介 Git是目前流行的分布式版本管理系统.它拥有两套版本库,本地库和远程库,在不进行合并和删除之类的操作时这两套版本库互不影响.也因此其近乎所有的操作都是本地执行,所以在断网的情况下任然可 ...

  7. XP系统如何把桌面图标变大

    右击桌面,属性,外观,高级,在项目里面找到图标,大小改为你喜欢的样式.   我测试的结果是:图标大小改为42,字体大小改为8,图标垂直间距改为100,水平间距改为54效果不错.

  8. VUE 数组更新

    1.数据方法分类: (1)原数组改变 push pop unshift shift reverse sort splice (2)原数组未变,生成新数组 slice concat filter map ...

  9. jQuery-mobile 学习笔记之三(事件监听)

    续上 触摸事件 - 当用户触摸屏幕时触发(敲击和滑动) 滚动事件 - 当上下滚动时触发 方向事件 - 当设备垂直或水平旋转时触发 页面事件 - 当页面被显示.隐藏.创建.载入以及/或卸载时触发 一.初 ...

  10. Patterns-Flyweight

    最近在组里讨论设计模式,第一个是享元模式. 自己贴了一篇这个文章:http://www.cnblogs.com/rush/archive/2011/10/01/2197785.html 感觉这篇讲的不 ...