Skip to content

Instantly share code, notes, and snippets.

@shiponcs
Created February 25, 2023 17:57
Show Gist options
  • Save shiponcs/2af62bbcb7ae4be60180871cb86f12be to your computer and use it in GitHub Desktop.
Save shiponcs/2af62bbcb7ae4be60180871cb86f12be to your computer and use it in GitHub Desktop.
Remove All Adjacent Duplicates In String- solve using stack
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