Created
April 4, 2024 03:56
-
-
Save codertcet111/89feb0c98eb0a78208e0d461f276a596 to your computer and use it in GitHub Desktop.
Leetcode 49 Group Anagram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Leetcode 49 Group Anagram | |
# @param {String[]} strs | |
# @return {String[][]} | |
def group_anagrams(strs) | |
sum_ascii_hash = {} | |
strs.each_with_index do |str, i| | |
sorted_aa = str.chars.sort.join | |
sum_ascii_hash["#{sorted_aa}"] ? sum_ascii_hash["#{sorted_aa}"] << i : sum_ascii_hash["#{sorted_aa}"] = [i] | |
end | |
sum_ascii_hash.values.map{|ind_arr| ind_arr.map{|ind| strs[ind]}} | |
end | |
# Partially correct approach by calculating ascii value | |
# def old_group_anagrams(strs) | |
# sum_ascii_hash = {} | |
# strs.each_with_index do |str, i| | |
# sum_key = str.split("").uniq.sum { |char| char.ord } | |
# Ignore: #sum_key = str.split("").sum { |char| char.ord } | |
# Ignore: #sum_key = str.split("").each_with_index.map{|char, i| char.ord * i}.sum | |
# sum_ascii_hash["#{sum_key}"] ? sum_ascii_hash["#{sum_key}"] << i : sum_ascii_hash["#{sum_key}"] = [i] | |
# end | |
# sum_ascii_hash.values.map{|ind_arr| ind_arr.map{|ind| strs[ind]}} | |
# end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment