Compress String
Given a string lowercase alphabet s
, eliminate consecutive duplicate characters from the string and return it.
That is, if a list contains repeated characters, they should be replaced with a single copy of the character. The order of the elements should not be changed.
Constraints
0 ≤ n ≤ 100,000
wheren
is the length ofs
https://binarysearch.com/problems/Compress-String
ExamplesPermalink
Example 1Permalink
Input
- s =
a
Output
- answer =
a
Example 2Permalink
Input
- s =
aaaaaabbbccccaaaaddf
Output
- answer =
abcadf
SolutionPermalink
string solve(string s) | |
{ | |
if (s.empty()) | |
return s; | |
ostringstream o; | |
char prev = s[0]; | |
int idx = 1; | |
o << prev; | |
while (idx < s.length()) | |
{ | |
if (s[idx] != prev) | |
{ | |
o << s[idx]; | |
prev = s[idx]; | |
} | |
idx++; | |
} | |
return o.str(); | |
} |
Leave a comment