Created
February 25, 2023 17:57
-
-
Save shiponcs/2af62bbcb7ae4be60180871cb86f12be to your computer and use it in GitHub Desktop.
Remove All Adjacent Duplicates In String- solve using stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string removeDuplicates(string toCleanUp) { | |
std:stack< char > str_stack; | |
for(char x : toCleanUp) { | |
if( !str_stack.empty() && x == str_stack.top() ) str_stack.pop(); | |
else str_stack.push( x ); | |
} | |
string res; | |
res.reserve(str_stack.size()); // reserve the space so that the concatenation speeds up. | |
while( !str_stack.empty() ) { | |
res += str_stack.top(); | |
str_stack.pop(); | |
} | |
reverse(res.begin(), res.end()); | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment