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. nodejs第一个练习:用Node.js建HTTP服务器

    这是官方的一个例子, 在F盘建立一个tinyphp.js文件,内容: var http = require('http'); http.createServer(function (req, res) ...

  2. fiddler抓取手机上https数据配置和失败的解决办法

    1. 设置fiddler,Tools-Options...      抓取https的话,勾选红框中的内容 2. fiddler默认监听端口8888 3. 查看本机IP 4. 打开手机 设置-无线局域 ...

  3. 基于Python的交互式访问

    应用迁移中遇到一些有特殊要求的应用,比如需要通过交互生成一些新的config文件,然后启动应用需要依赖于这些文件,这样在构建镜像的时候基本上是没有办法把这些文件固定的,因为他需要根据运行环境去进行动态 ...

  4. 三.rocketmq-console

    ⦁    rocketmq-console来源于https://github.com/rocketmq/rocketmq-console 1.配置IP 2.启动运行:出现此信息则表示成功  访问:in ...

  5. grep:字符串查找

    转自: http://www.cnblogs.com/peida/archive/2012/12/17/2821195.html Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达 ...

  6. mysql 数据库缓存调优之解决The total number of locks exceeds the lock table size错误

    环境: mysql5.6.2  主从同步(备注:需操作主库和从库) 一.InnoDB表执行大批量数据的更新,插入,删除操作时会出现这个问题,需要调整InnoDB全局的innodb_buffer_poo ...

  7. C#程序输出信息到调试窗口的几种方式

    网站项目: System.Diagnostics.Debug.WriteLine("aaa"); 控制项目:Console.WriteLine("bbb"); ...

  8. EPF与Myeclipse 增强代码自动智能提示

    摘自: http://blog.csdn.net/ylchou/article/details/7639467 数字证书文件,导入用. EPF文件是著名的软件开发工具——Eclipse(IDE)的配置 ...

  9. Newtonsoft.Json.4.5.11使用方法总结---反序列化json字符串

    写在开头: 最近项目需求,需要在C#中处理json字符串,毫不犹豫的下载了Newtonsoft.Json 4.5.11(2012.12.17)http://json.codeplex.com/,然后百 ...

  10. Fedora 中的容器技术:systemd-nspawn

    本文将说明你可以怎样使用 Fedora 中各种可用的容器技术和学习“systemd-nspawn”的相关知识. 容器是什么? 一个容器就是一个用户空间实例,它能够在与托管容器的系统(叫做宿主系统)相隔 ...