Alternating Characters

  • + 0 comments

    php

    function alternatingCharacters($s) {
        // Write your code here
        $stack = [];
        $deletions = 0;
        for ($i = 0; $i < strlen($s); $i++) {
            if (count($stack) === 0) {
                $stack[] = $s[$i];
            } else {
                $last = $stack[count($stack) - 1];
                if ($last === $s[$i]) {
                    $deletions++;
                } else {
                    $stack[] = $s[$i];
                }
            }
        }
        return $deletions;
    }