(919) 964-9842
(919) 964-9842

Hackerrank in PHP: Alternating Characters

This one was pretty straightforward but I got messed up on not actually removing the duplicate. So I had an unset() call in there to remove the duplicate and it was throwing off my numbers. In this case, they just want you to count the duplicates, not remove them.

Let's find the duplicate characters in a given string!

1
2
3
4
5
6
7
8
9
10
11
12
13
// Complete the alternatingCharacters function below.
function alternatingCharacters($s) {
    $multiples = 0;
    $string = str_split($s);

    for($i = 0; $i < count($string); $i++) {
        if(isset($string[$i + 1]) && $string[$i] == $string[$i + 1]) {
            $multiples++;
        }
    }

    return $multiples;
}

First we convert the string into an array, and loop through the total number of letters in the string using count(). Then, compare the two letters that are next to each other. If they are the same, it's a multiple, so increase the count. Don't unset() the multiple! Your numbers will be off.

That's it on this one.

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *