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)
|
|
|
|
array = strA.concat(" ", strB).split(" ")
|
|
|
|
hash = Hash.new(0)
|
|
|
|
result = []
|
|
|
|
|
|
|
|
array.each do |word|
|
|
|
|
if hash[word]
|
|
|
|
hash[word] += 1
|
|
|
|
else
|
|
|
|
hash[word] = 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
hash.each do |k, v|
|
|
|
|
if v < 2
|
|
|
|
result.push(k)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
result
|
|
|
|
end
|
|
|
|
|
2021-05-15 01:53:05 +02:00
|
|
|
puts find_uncommon_words("this apple is sweet", "this apple is sour")
|
|
|
|
# => ["sweet", "sour"]
|
|
|
|
|
|
|
|
puts find_uncommon_words("apple apple", "banana")
|
|
|
|
# => ["banana"]
|