2 つの文字列が与えられた場合、それらが互いのアナグラムであるかどうかを判断したいと思います。これが私が思いついた解決策です:
# 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)
上記を考慮して、ソリューション全体の効率を、O(n log n)
並べ替えの効率が最も高いものとして分類しました。よりも効率的なこれを行うためのより良い方法はありO(n log n)
ますか?