See the original problem on HackerRank.
Solutions
This problem can be solved by counting the number of equal adjacent characters:
|
|
This is an application of zip | map | reduce pattern:
|
|
We have the opportunity to play with the standard library. For example, if we erase all the adjacent equal characters, the answer is given by the difference between the original length of the string and the length of the new string:
|
|
Another similar solution does not erase anything, instead it only counts the number of rearranged characters:
|
|
Although the last two solutions modify the string, they gave us the opportunity to learn how to erase all the adjacent equal characters from a string and also to see what unique
really does.
A simple solution in Haskell is using the group
function to split the string
in groups of the same character and subtract the number of groups from the
length of the string.
|
|
Or you can count the number of equal adjacent characters:
|
|
Make it shorter with zipWith
:
|
|
With foldl
:
|
|