Given a string which contains only lowercase letters, remove duplicate consecutive letters so that every letter appear once and only once.
The right answer in Ruby is to use String#squeeze:
>> "abbaaaaccc".squeeze('a-z')
=> "abac"
>> "abbaa".squeeze('a-z')
=> "aba"
If you want to solve the problem academically, the approach to use is essentially recursively walking the string and comparing letters, slicing off duplicates as you go.
def dedupe(str)
return if str.empty?
str.split('').each_with_index do |char, i|
if str[i] == str[i + 1]
str.slice!(i + 1)
return dedupe(str)
end
end
str
end
>> dedupe "abbaaaaccc"
=> "abac"