Merge pull request #149 from jsca-kwok/jk-uncommon-words

Uncommon words algorithm
This commit is contained in:
Vitor Oliveira 2021-05-20 22:55:18 -07:00 committed by GitHub
commit 5756afbd95
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 0 deletions

View file

@ -55,6 +55,7 @@
* [Good Pairs](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/good_pairs.rb) * [Good Pairs](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/good_pairs.rb)
* [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/richest_customer_wealth.rb) * [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/richest_customer_wealth.rb)
* [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/two_sum.rb) * [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/two_sum.rb)
* [Uncommon Words](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/uncommon_words.rb)
* Linked Lists * Linked Lists
* [Circular Linked List](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/linked_lists/circular_linked_list.rb) * [Circular Linked List](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/linked_lists/circular_linked_list.rb)
* [Doubly Linked List](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/linked_lists/doubly_linked_list.rb) * [Doubly Linked List](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/linked_lists/doubly_linked_list.rb)

View file

@ -0,0 +1,48 @@
# Challenge name: Uncommon words from two sentences
#
# We are given two sentences A and B.
# (A sentence is a string of space separated words.
# Each word consists only of lowercase letters.)
#
# A word is uncommon if it appears exactly once in one of the sentences,
# and does not appear in the other sentence.
#
# Return a list of all uncommon words.
# You may return the list in any order.
#
# Example 1:
# Input: A = "this apple is sweet", B = "this apple is sour"
# Output: ["sweet","sour"]
#
# Example 2:
# Input: A = "apple apple", B = "banana"
# Output: ["banana"]
#
# Approach 1: Hash
#
# Time Complexitiy: O(n)
def find_uncommon_words(strA, strB)
array = strA.concat(" ", strB).split(" ")
hash = Hash.new(0)
result = []
array.each do |word|
hash[word] += 1
end
hash.each do |k, v|
if v < 2
result.push(k)
end
end
result
end
puts find_uncommon_words("this apple is sweet", "this apple is sour")
# => ["sweet", "sour"]
puts find_uncommon_words("apple apple", "banana")
# => ["banana"]