给定两个字符串,我想确定它们是否是彼此的字谜。这是我想出的解决方案:
# output messages
def anagram
puts "Anagram!"
exit
end
def not_anagram
puts "Not an anagram!"
exit
end
# main method
if __FILE__ == $0
# read two strings from the command line
first, second = gets.chomp, gets.chomp
# special case 1
not_anagram if first.length != second.length
# special case 2
anagram if first == second
# general case
# Two strings must have the exact same number of characters in the
# correct case to be anagrams.
# We can sort both strings and compare the results
if first.chars.sort.join == second.chars.sort.join
anagram
else
not_anagram
end
end
但我认为可能有更好的。我分析了这个方案的效率,得出了:
chars
: 将字符串拆分为字符数组O(n)
sort
:按字母顺序对字符串进行排序,我不知道如何在 Ruby 中实现排序,但我认为O(n log n)
这是众所周知的排序效率join
: 从一个字符数组构建一个字符串O(n)
==
:字符串比较本身必须检查字符串的每个字符2*O(n)
Given the above, I categorized the efficiency of the entire solution as O(n log n)
since sorting had the highest efficiency. Is there a better way to do this that is more efficient than O(n log n)
?