leetcode 443. String Compression
程序员文章站
2024-03-13 22:17:28
...
#include<stack>
class Solution {
public:
int compress(vector<char>& chars) {
char tmp=chars[0];
int count =1;
int sum = 0;
int j=0;
for(int i =1;i<=chars.size();i++)
{
if(i==chars.size()||tmp!=chars[i])
{
sum ++;
chars[j]=tmp;
j++;
if(count!=1)
{
stack<int> l;
while(count)
{
int r = count%10;
l.push(r);
count = count/10;
sum++;
}
while(!l.empty())
{
chars[j] = l.top()+'0';
j++;
l.pop();
}
}
if(i!=chars.size())tmp = chars[i];
count = 1;
}
else if(tmp==chars[i])count ++;
}
return sum;
}
};
#include<stack>
class Solution {
public:
int compress(vector<char>& chars) {
char tmp=chars[0];
int count =1;
int sum = 0;
int j=0;
for(int i =1;i<=chars.size();i++)
{
if(i==chars.size()||tmp!=chars[i])
{
sum ++;
chars[j]=tmp;
j++;
if(count!=1)
{
string s = to_string(count);
for(int k=0;k<s.size();k++) {chars[j]=s[k];j++;sum++;}
}
if(i!=chars.size())tmp = chars[i];
count = 1;
}
else if(tmp==chars[i])count ++;
}
return sum;
}
};
推荐阅读
-
leetcode 443. String Compression
-
[leetcode]443. String Compression
-
[leetcode]443. String Compression
-
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