[leetcode]443. String Compression
程序员文章站
2024-03-13 22:13:04
...
[leetcode]443. String Compression
Analysis
everyday is the first day of your rest life—— [间歇性迷茫+2~]
Given an array of characters, compress it in-place.
压缩字符串,基本上看样例就能明白意思了。
Implement
class Solution {
public:
int compress(vector<char>& chars) {
if(chars.size() == 0)
return 0;
int len = chars.size();
int cnt = 1;
int res = 1;
char t = chars[0];
for(int i=1; i<len; i++){
if(chars[i] == t)
cnt++;
else{
if(cnt > 1){
string s = to_string(cnt);
for(auto c:s)
chars[res++] = c;
}
cnt = 1;
t = chars[i];
chars[res++] = t;
}
}
if(cnt > 1){
string s = to_string(cnt);
for(auto c:s)
chars[res++] = c;
}
chars.resize(res);
return res;
}
};
推荐阅读
-
[leetcode]443. String Compression
-
leetcode 1349 Maximum Students Taking Exam (dp state compression)
-
1.6 String Compression
-
UVA 1351 - String Compression
-
leetcode (String Compression)
-
LeetCode-String Compression
-
[String][3]Leetcode125. Valid Palindrome
-
leetcode 345 Reverse Vowels of a String
-
Leetcode学习(38)—— First Unique Character in a String
-
Leetcode 344. Reverse String--输入字符数组,倒序输出