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

1 Answer

0 votes
function remove_adjacent_duplicates(string $s): string {
    $stack = [];

    foreach (str_split($s) as $ch) {
        if (!empty($stack) && end($stack) === $ch) {
            array_pop($stack);   // pop
        } else {
            $stack[] = $ch;      // push
        }
    }

    return implode('', $stack);
}

$s = "abbacccada";
echo remove_adjacent_duplicates($s);   



/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...