mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-25 21:58:57 +01:00
Merge pull request #149 from jsca-kwok/jk-uncommon-words
Uncommon words algorithm
This commit is contained in:
commit
5756afbd95
2 changed files with 49 additions and 0 deletions
|
@ -55,6 +55,7 @@
|
|||
* [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)
|
||||
* [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
|
||||
* [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)
|
||||
|
|
48
data_structures/hash_table/uncommon_words.rb
Normal file
48
data_structures/hash_table/uncommon_words.rb
Normal 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"]
|
Loading…
Reference in a new issue