Re: [闲聊] 每日LeetCode

楼主: idiont (supertroller)   2023-03-02 09:40:13
443. String Compression
给定一个 character array: chars,需要将他压缩,
把原本的阵列改成压缩后的结果,并回传它的长度。
压缩方式如下:
从一个空的字串 s 开始,
原本的 chars 可以由左至右分成多个 group,
每个 group 都由最长连续的相同字符组成,
如果这个 group 的大小为 1,则将该字符单独加入 s,
如果大小大于 1,则将该字符以及出现次数加入 s。
额外规定: 只使用常数大小的额外空间
Example 1:
Input: chars = ["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:
"aabbccc" 压缩成 "a2b2c3"
长度为 6 并将字串拆成 6 个字符放到 chars 的前6个位置。
Example 2:
Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be:
["a"]
Explanation:
"a" 只单独出现一个,不需要加入出现次数,因此压缩后还是 "a"。
Example 3:
Input: chars = ["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:
"abbbbbbbbbbbb",a 出现 1 次,b 出现 12 次,压缩后为 "ab12"。
解题思路:
记住当前比对的是哪个字符,出现几次,
如果遇到不同字符就把前面的结果直接放进原始阵列就好,
压缩后一定会变小或是不变,所以不会盖到还没处理到的资料。
C++ code:
class Solution {
public:
int compress(vector<char>& chars) {
char temp = chars[0];
int count = 0, pos = 0;
for(int i = 0; i < chars.size(); i++){
if(chars[i] == temp) count++;
if(i + 1 >= chars.size() || chars[i] != chars[i+1]){
chars[pos++] = temp;
if(count > 1){
// input size <= 2000
static vector<int> digits{1000, 100, 10, 1};
for(auto j : digits){
if(count >= j) chars[pos++] = (count / j % 10) + '0';
}
}
if(i + 1 < chars.size()){
temp = chars[i+1];
count = 0;
}
}
}
return pos;
}
};
作者: dustsstar79 (穆)   2023-03-02 09:46:00
大师
作者: Rushia (みけねこ的鼻屎)   2023-03-02 12:33:00
大师
作者: NTHUlagka (拉卡)   2023-03-02 12:40:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com