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 ...
随机推荐
- Java_导出Excel
导出的Excel标题.Sheet名称.数据内容都可以使用中文 一.pom.xml引入jar包 1 2 3 4 5 <dependency> <groupId ...
- Linux /sbin/service脚本一个基本无影响的bug
CentOS提供了一个启动服务的功能:service [service name] (start|stop|restart|...),此功能的执行脚本为/sbin/service. 今天看了下此脚本, ...
- Openshift 用户,角色和RBAC
OCP中的权限管理沿用的Kubernetes RBAC机制,授权模式主要取决于下面几个因数 Rules 针对主要对象的操作权限,比如建立Pod Sets of permitted verbs on a ...
- ubuntu 安装ODOO时的python的依赖
sudo apt-get install graphviz ghostscript postgresql-client python-dateutil python-feedparser python ...
- hdu 4893Wow! Such Sequence!
多校第三场 7题..线段树A的 #include <cstdio> #include <cstring> #include <iostream> #include ...
- java运行shell命令,chmod 777 xxx,改变权限无效的解决的方法。
在java程序中运行shell命令,改变文件的权限.能够在命令行中运行 chmod 777 <span style="font-family: Arial, Helvetica, sa ...
- profile_oracle设置某用户password永只是期
原创作品.出自 "深蓝的blog" 博客,深蓝的blog:http://blog.csdn.net/huangyanlong/article/details/46888139 or ...
- jQuery Recipies - 使用map来过滤对应的元素集
<table id="tblEmployee" class="normal_table"> <tr> <td>Employe ...
- Android Exception 9(requestFeature() must be called before adding content)
08-05 17:36:12.799: W/System.err(10378): java.lang.reflect.InvocationTargetException08-05 17:36:12.7 ...
- struts result动态结果集 带参数的结果集
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC &qu ...