mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Valid anagram: hash table approach
This commit is contained in:
parent
a472f9a6ff
commit
4674c2d97b
2 changed files with 56 additions and 1 deletions
|
@ -15,7 +15,7 @@
|
|||
# @return {Boolean}
|
||||
|
||||
#
|
||||
# Approach 1: Sort and Compare
|
||||
# Approach: Sort and Compare
|
||||
#
|
||||
# Complexity analysis:
|
||||
#
|
||||
|
|
55
data_structures/hash_table/anagram_checker.rb
Normal file
55
data_structures/hash_table/anagram_checker.rb
Normal file
|
@ -0,0 +1,55 @@
|
|||
# Challenge name: Is anagram
|
||||
#
|
||||
# Given two strings s and t , write a function to determine
|
||||
# if t is an anagram of s.
|
||||
#
|
||||
# Note:
|
||||
# You may assume the string contains only lowercase alphabets.
|
||||
#
|
||||
# Follow up:
|
||||
# What if the inputs contain unicode characters?
|
||||
# How would you adapt your solution to such case?
|
||||
#
|
||||
# @param {String} s
|
||||
# @param {String} t
|
||||
# @return {Boolean}
|
||||
|
||||
#
|
||||
# Approach: Hash table
|
||||
#
|
||||
# Complexity analysis:
|
||||
#
|
||||
# Time complexity: O(n). Time complexity is O(n) since accessing the counter table is a constant time operation.
|
||||
# Space complexity: O(1). Although we do use extra space, the space complexity is O(1) because the table's size stays constant no matter how large n is.
|
||||
#
|
||||
def is_anagram(s, t)
|
||||
s_length = s.length
|
||||
t_length = t.length
|
||||
counter = Hash.new(0)
|
||||
|
||||
return false unless s_length == t_length
|
||||
|
||||
(0...s_length).each do |i|
|
||||
counter[s[i]] += 1
|
||||
counter[t[i]] -= 1
|
||||
end
|
||||
|
||||
counter.each do |k, v|
|
||||
return false unless v == 0
|
||||
end
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
s = 'anagram'
|
||||
t = 'nagaram'
|
||||
puts(is_anagram(s, t))
|
||||
# => true
|
||||
s = 'rat'
|
||||
t = 'car'
|
||||
puts(is_anagram(s, t))
|
||||
# => false
|
||||
s = 'a'
|
||||
t = 'ab'
|
||||
puts(is_anagram(s, t))
|
||||
# => false
|
Loading…
Reference in a new issue