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. BlackBerry10 开发环境搭建

    最近开始学习BlackBerry10的开发,黑莓10系统是2013年1月30日黑莓公司正式发布的,目前网上资料比较少,这篇博客的内容基本上是按照官网上的文档写的.BlackBerry10目前支持C/C ...

  2. [Eclipse插件] Eclipse中如何安装和使用GrepCode插件

    Java是开源的世界,如何快速的搜索到你需要的Java源码呢?2009年7月17日,GrepCode团队发布了一个有趣的 Java源码搜索引擎-GrepCode .与现有的各种搜索引擎相比,Java源 ...

  3. iOS:在使用Cocoapods安装shareSDK时出现的link路径错误

    CocoaPods 错误 target overrides the `OTHER_LDFLAGS`... Xcode 升级到 6.0 后,更新 CocoaPods,出现了如下的警告 [!] The ` ...

  4. Maven中的SNAPSHOT版本和正式版本理解

    Maven中建立的依赖管理方式基本已成为Java语言依赖管理的事实标准,Maven的替代者Gradle也基本沿用了Maven的依赖管理机制.在Maven依赖管理中,唯一标识一个依赖项是由该依赖项的三个 ...

  5. [TypeScript] Work with DOM Elements in TypeScript using Type Assertions

    The DOM can be a bit tricky when it comes to typing. You never really know exactly what you're going ...

  6. dubbo-monitor安装监控中心,管理控制台安装网页一直访问不到,解决bug的方式记录

    问题再现 第一步,重启机器 第二步,按照dubbo-monitor需要开启的服务,顺序逐一进行启动,之前的推翻全部重新再走一遍就通了,千万不能死磕...很浪费时间.... 通过打印日志追踪问题的所在. ...

  7. 基于paramiko进行远程执行Linux命令

    直接贴一段代码import paramiko class remote_start(object): def __init__(self,host,username,pwd): self.ssh = ...

  8. ES6 const用法

    1.const声明一个只读的常量.一旦声明,常量的值就不能改变. 2.const的作用域与let命令相同:只在声明所在的块级作用域内有效. 3.const命令声明的常量也是不提升,只能在声明的位置后面 ...

  9. maven的profile 目录、变量打包

    <project> <build> <finalName>maven-project</finalName> <resources> < ...

  10. oracle 某一字段取反

    --某一位取反select id ,flag,(flag + 1) - BITAND(flag, 1) * 2 from SYS_INFO t UPDATE SYS__INFO SET FLAG=(( ...