LeetCode/solutions/443. String Compression.md

40 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [443. String Compression](https://leetcode.com/problems/string-compression/description/)
# 思路
根据题意压缩字符串。
用res记录当前处理过的字符串压缩后的长度num记录当前字符出现了多少次。
# C++
```
class Solution {
public:
int compress(vector<char>& chars) {
int res = 0, tmp, num = 1; // num初始为1
for(int i = 1; i < chars.size(); i++){
if(chars[i] == chars[i - 1]) num++;
else{
chars[res++] = chars[i - num];
if(num == 1) continue; // 若出现次数仅为1则后面不加“1”
// 以下5行将int型转为char型也可用string s = to_string(num)转,不过好像慢一些
tmp = res;
while(num != 0){
chars[res++] = (num % 10 + '0');
num /= 10;
}
reverse(chars.begin() + tmp, chars.begin() + res);
num = 1;
}
}
chars[res++] = chars[chars.size() - 1];
if(num > 1){
tmp = res;
while(num != 0){
chars[res++] = (num % 10 + '0');
num /= 10;
}
reverse(chars.begin() + tmp, chars.begin() + res);
}
return res;
}
};
```