How to remove all adjacent duplicate characters from a string until no more can be removed in C++

1 Answer

0 votes
#include <iostream>
#include <string>

std::string remove_adjacent_duplicates(const std::string& s) {
    std::string stack;  
    stack.reserve(s.size());  // avoid reallocations

    for (char ch : s) {
        if (!stack.empty() && stack.back() == ch) {
            stack.pop_back();   
        } else {
            stack.push_back(ch); 
        }
    }

    return stack;
}

int main() {
    std::string s = "abbacccada";
    
    std::cout << remove_adjacent_duplicates(s) << "\n";  
}



/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...