Merge pull request #111 from jsca-kwok/jk-remove-vowels

Add remove vowels from a string algorithm
This commit is contained in:
Vitor Oliveira 2021-03-29 14:54:41 -07:00 committed by GitHub
commit 0bf87b3fe1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 77 additions and 0 deletions

View file

@ -14,6 +14,7 @@
* [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb)
* [Jewels And Stones](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/jewels_and_stones.rb)
* [Remove Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/remove_elements.rb)
* [Remove Vowels](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/remove_vowels.rb)
* [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/richest_customer_wealth.rb)
* [Shuffle Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/shuffle_array.rb)
* [Single Number](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/single_number.rb)

View file

@ -0,0 +1,76 @@
# Challenge name: Remove vowels from a string
#
# Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u'
# from it, and return the new string.
#
# Example 1:
# Input: s = "leetcodeisacommunityforcoders"
# Output: "ltcdscmmntyfrcdrs"
#
# Example 2:
# Input: s = "aeiou"
# Output: ""
#
# @param {String} s
# @return {String}
#
# Approach 1: Brute Force
#
# Time Complexity: O(n)
#
def remove_vowels(s)
result_array = []
s.downcase!
start_array = s.split('')
start_array.each do |letter|
if letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u'
result_array.push(letter)
end
end
result_array.join('')
end
s = 'leetcodeisacommunityforcoders'
puts(remove_vowels(s))
# => "ltcdscmmntyfrcdrs"
s = 'aeiou'
puts(remove_vowels(s))
# => ""
#
# Approach 2: Regex
#
# Time Complexity: O(n)
#
def remove_vowels(s)
vowels = /[aeiou]/i
s.gsub!(vowels, '')
s
end
s = 'leetcodeisacommunityforcoders'
puts(remove_vowels(s))
# => "ltcdscmmntyfrcdrs"
s = 'aeiou'
puts(remove_vowels(s))
# => ""
#
# Approach 3: Using Ruby .delete() method
#
# Time Complexity: O(n)
#
def remove_vowels(s)
s.downcase.delete('aeiou')
end
s = 'leetcodeisacommunityforcoders'
puts(remove_vowels(s))
# => "ltcdscmmntyfrcdrs"
s = 'aeiou'
puts(remove_vowels(s))
# => ""