Skip to content

Instantly share code, notes, and snippets.

@mckern
Last active June 2, 2021 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mckern/5625f45c268a90e74db78d9f01f9dd21 to your computer and use it in GitHub Desktop.
Save mckern/5625f45c268a90e74db78d9f01f9dd21 to your computer and use it in GitHub Desktop.

Challenge

Given a string which contains only lowercase letters, remove duplicate consecutive letters so that every letter appear once and only once.

Easy Solution

The right answer in Ruby is to use String#squeeze:

>> "abbaaaaccc".squeeze('a-z')
=> "abac"
>> "abbaa".squeeze('a-z')
=> "aba"

Academic solution

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment