Conversation
|
|
||
| Acceptされてから, 文字列自体をソートしてキーにしまえば一意になることに気がついたので実装を変更. (文字列はhashableなのでキーにできる) | ||
| 時間計算量: O(N*L*logL) N: strs.length, L: strs[i].length | ||
| `str()`でL^2かかる? |
| ## Step1 | ||
| 同じ文字構成になる単語を分類する問題. 文字構成が同じということは各文字をカウントしてその結果が同じ単語をグループにすれば解けそう. オーソドックスにhashmapを用いて文字の出現をカウントする. | ||
| また,文字構成が同じ単語をグループにするためにhashmapを用いる. | ||
| hashmapはそのままでは`hashable`(immutable)ではないので,dictのキーにすることができない. そこで,dictの要素から無理やりユニークなハッシュ値を作成してしまえばいいのではと考え,{文字}{出現回数}の列をキーとした. |
There was a problem hiding this comment.
ランレングス圧縮っぽいですね。
| return dict(sorted(char_to_freq.items())) | ||
|
|
||
| def dict_to_hash(char_to_freq): | ||
| hash = "" |
There was a problem hiding this comment.
"hash"は組み込み関数と被っているので避けたいですね。
| >また、入力が、小文字アルファベットでないものが来たときに、どのような振る舞いをするか、どのような振る舞いをするべきかは追加質問が来てもおかしくないでしょう。 | ||
|
|
||
| `ord`を使った解法でまずは解いてみる. 時間計算量はO(NL), 空間計算量O(NL). | ||
| memo: アルファベット小文字のUnicodeポイントは97 ~ 122, 大文字は65 ~ 50らしい |
There was a problem hiding this comment.
| memo: アルファベット小文字のUnicodeポイントは97 ~ 122, 大文字は65 ~ 50らしい | |
| memo: アルファベット小文字のUnicodeポイントは97 ~ 122, 大文字は65 ~ 90らしい |
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| counter_to_anagrams = defaultdict(list) | ||
| NUM_CHARACTERS = 26 |
There was a problem hiding this comment.
26がどこから来たのかを明示するために、len(string.ascii_lowercase)と書いても良いでしょう。
https://docs.python.org/ja/3/library/string.html#string.ascii_lowercase
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| uniqeword_to_anagrams = defaultdict(list) | ||
| for word in strs: | ||
| uniqeword_to_anagrams["".join(sorted(word))].append(word) |
There was a problem hiding this comment.
uniqe -> unique
| uniqeword_to_anagrams["".join(sorted(word))].append(word) | |
| unique_word_to_anagrams["".join(sorted(word))].append(word) |
|
|
||
| def dict_to_hash(char_to_freq): | ||
| hash = "" | ||
| for char, freq in char_to_freq.items(): |
There was a problem hiding this comment.
charはCやJavaの組み込み型と被るので自分は避けます。
cやchがよくみます。
蛇足ですが、chr()はPythonの組み込み関数で、ord()の逆操作(コードポイント -> 文字へ変換)をする関数です。
| ```py | ||
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| counter_to_anagrams = defaultdict(list) |
There was a problem hiding this comment.
count_to_anagramsの方が自然かなと思いました。英語に弱いので自分でもなぜ違和感を感じたのかはっきりしなかったのですが、counterは計算する人、計数器という意味があるそうで、key_value形式のkeyに使うのであればcount(数える)の方が自然に感じるという感覚です。
https://ejje.weblio.jp/content/counter
解く問題
Group Anagrams
次に解く問題
Intersection Of Two Arrays