Python アナグラム チェッカー

Python で文字の構成を比較することで、2 つの文字列がアナグラムであるかどうかを確認します。

エディターで試してみる

概要

2 つの文字列が、異なる順序で配置されていても、同じ頻度で同じ文字が含まれている場合 (例: 「listen」と「silent」) はアナグラムです。

アナグラムをチェックするエレガントな方法は、文字列をクリーンアップし (空白文字と小文字を削除し)、文字を並べ替えて、並べ替えられたリストが同一かどうかを確認することです。

この並べ替えアプローチは、O(k log k) 時間で実行されます。ここで、k は文字列の長さであり、短いテキストのチェックに最適です。

コードと実行の出力

文字ソートによるアナグラムステータスの単語の組み合わせをチェックします。

def is_anagram(str1, str2):
    s1 = sorted(str1.lower().replace(" ", ""))
    s2 = sorted(str2.lower().replace(" ", ""))
    return s1 == s2

word1, word2 = "listen", "silent"
print(f"Are '{word1}' and '{word2}' anagrams? {is_anagram(word1, word2)}")

word3, word4 = "hello", "world"
print(f"Are '{word3}' and '{word4}' anagrams? {is_anagram(word3, word4)}")
端子出力
Are 'listen' and 'silent' anagrams? True
Are 'hello' and 'world' anagrams? False

段階的な実装

  • テキスト分析および言語比較エンジン
  • 文字列パズルの設計と検証システム
  • 技術面接のコーディングタスク

よくある質問

これを O(n) 線形時間で解決する方法はありますか?

はい!並べ替える代わりに、ハッシュ マップまたは Python の「collections.Counter」を使用して文字の頻度をカウントし、結果の頻度マップを比較することができます。

関連トピック