TheAlgorithms-Ruby/data_structures/hash_table/uncommon_words.rb

47 lines
1,021 B
Ruby
Raw Normal View History

2021-05-13 21:09:01 +02:00
# 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"
2021-05-15 01:36:04 +02:00
# Output: ["banana"]
#
# Approach 1: Hash
#
# Time Complexitiy: O(n)
def find_uncommon_words(strA, strB)
2021-09-03 22:24:58 +02:00
array = strA.concat(' ', strB).split(' ')
2021-05-15 01:36:04 +02:00
hash = Hash.new(0)
result = []
array.each do |word|
hash[word] += 1
2021-05-15 01:36:04 +02:00
end
hash.each do |k, v|
2021-09-03 22:24:58 +02:00
result.push(k) if v < 2
2021-05-15 01:36:04 +02:00
end
result
end
2021-09-03 22:24:58 +02:00
puts find_uncommon_words('this apple is sweet', 'this apple is sour')
2021-05-15 01:53:05 +02:00
# => ["sweet", "sour"]
2021-09-03 22:24:58 +02:00
puts find_uncommon_words('apple apple', 'banana')
# => ["banana"]