443. String Compression
问题描述
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
I**nput:**
[“a”,”a”,”b”,”b”,”c”,”c”,”c”]
Output:
Return 6, and the first 6 characters of the input array should be: [“a”,”2”,”b”,”2”,”c”,”3”]
Explanation:
“aa” is replaced by “a2”. “bb” is replaced by “b2”. “ccc” is replaced by “c3”.
Example 2:
Input:
[“a”]
Output:
Return 1, and the first 1 characters of the input array should be: [“a”]
Explanation:
Nothing is replaced.
Example 3:
Input:
[“a”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”]
Output:
Return 4, and the first 4 characters of the input array should be: [“a”,”b”,”1”,”2”].
Explanation:
Since the character “a” does not repeat, it is not compressed. “bbbbbbbbbbbb” is replaced by “b12”.
Notice each digit has it’s own entry in the array.
Note:
1. All characters have an ASCII value in [35, 126]
.
2. 1 <= len(chars) <= 1000
.
思路分析
给一个char的数组,其中有重复的数字,将这个string进行压缩,如果字符连续出现的次数大于一次,就用char+count的全字符形式来表示。要求用常数空间in-place完成。最后返回新string的长度。
使用快慢两个指针来遍历数组。慢指针current指向现在所在的字符,快指针i用来进行遍历,找应该放在current位的字符。
我们需要进行压缩的条件是,到达了数组最后一个元素或者i与i+1不同了。此时我们将current更新为i的值,然后判断cout的次数,如果大于1,那么就将count变为string后插入到current之后到位置。最后将count清零。
代码
class Solution {
public:
int compress(vector<char>& chars) {
int current = 0, count = 0;
for(int i = 0; i < chars.size(); i++){
count++;
if(i == chars.size() - 1 || chars[i] != chars[i + 1]){
chars[current++] = chars[i];
if(count != 1){
string temp = to_string(count);
for(char ch : temp){
chars[current++] = ch;
}
}
count = 0;
}
}
return --current;
}
};
时间复杂度:
空间复杂度:
反思
对于current指针的移动,要多加注意,我们可以理解为current处是空的:首先是出现不同字符时,将新的字符放在current后,current就可以移动了;然后时count转换为char时,也是放一个动一个。
同样的,对于count,正常情况下跟随icount,使用i == i+1的判断,可以帮助count简化情况。
上一篇: 最简单的计算器编码!
下一篇: 第一周学习笔记
推荐阅读
-
String、StringBuffer和StringBuilder区别
-
string '??54' (length=8)用什么函数能转换成int类型的?解决思路
-
PHP中奇妙的String
-
php文件压缩zlib.output_compression 和 ob_gzhandler,
-
Oracle中DBMS_RANDOM.STRING 的用法
-
string 类型约束的问题
-
switch case语句中能否作用在String,long上
-
php中simplexml_load_string使用实例分享
-
php中mysql_real_escape_string()函数的用法介绍
-
求mysql_real_escape_string()防注入详解