213. String Compression【easy】
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).
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】的更多相关文章
- 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 ...
- 213. String Compression【LintCode java】
Description Implement a method to perform basic string compression using the counts of repeated char ...
- 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 ...
- 606. Construct String from Binary Tree 【easy】
606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...
- 344. Reverse String【easy】
344. Reverse String[easy] Write a function that takes a string as input and returns the string rever ...
- 189. Rotate Array【easy】
189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = ...
- 551. Student Attendance Record I【easy】
551. Student Attendance Record I[easy] You are given a string representing an attendance record for ...
- 383. Ransom Note【easy】
383. Ransom Note[easy] Given an arbitrary ransom note string and another string containing letters f ...
- 657. Judge Route Circle【easy】
657. Judge Route Circle[easy] Initially, there is a Robot at position (0, 0). Given a sequence of it ...
随机推荐
- 30分钟LINQ教程【转】
千万别被这个页面的滚动条吓到!!! 我相信你一定能在30分钟之内看完它!!! 在说LINQ之前必须先说说几个重要的C#语言特性 一:与LINQ有关的语言特性 1.隐式类型 (1)源起 在隐式类型出现之 ...
- Struts2中的页面跳转
内容源自:Struts2中的页面跳转 一.全局页面的设置如果<package>包中的一些action都返回success,并且返回的页面都是同一个JSP页面,这样就可以配置全局的结果页面. ...
- [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer
With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...
- redis学习笔记——事件处理
Redis服务器是一个事件驱动程序,服务器需要处理以下两类事件: 文件事件(file event):Redis服务器通过套接字与客户端(或者其他Redis服务器)进行连接,而文件事件就是服务器对套接字 ...
- redis3.0.6安装配置
运行linux客户端 1 安装依赖 yum install gcc-c++ -y(安装gcc) 2 创建安装目录.编译.安装 mkdir -p /usr/local/redis(创建安 ...
- vue - utils.js
exports:导出功能函数或变量 module.exports:默认导出{} ------------------------------------------------------------ ...
- Win7下Python WEB环境搭建
环境介绍: Win7 64位 SP1 Python:2.7.6 网关接口:flup Nginx安装:http://blog.csdn.net/jacson_bai/article/details/46 ...
- Linux配置虚拟主机后,只能访问到主页怎么办?
Linux配置虚拟主机后,只能访问到主页怎么办? 今天配置了lamp后,添加了一个虚拟主机,配置http.conf后,增加虚拟主机,测试访问发现只有域名下能访问,ljt.com但是域名下所有的都访问不 ...
- Google 收购 Android 十周年 全面解读Android现状
--訪传智播客Android学科教学总监传智·平一指 Android以前是一家创立于旧金山的公司的名字,该公司于2005年8月份被Google收购,并从此踏上了飞速发展的道路.经过十年的发展,它已经发 ...
- ORA-01589: 要打开数据库则必须使用 RESETLOGS 或 NORESETLOGS 选项
产生这个的原因可能是由于数据库突然停止,没有来得及将缓存区中的LOG归档,导致下次开启时不能匹配日志文件. 数据库中的三个日志文件挨个试,第二个就匹配上了