Skip to content

49. Group Anagrams#2

Merged
t-ooka merged 10 commits intomainfrom
question/group-anagram
Jun 14, 2024
Merged

49. Group Anagrams#2
t-ooka merged 10 commits intomainfrom
question/group-anagram

Conversation

@t-ooka
Copy link
Copy Markdown
Owner

@t-ooka t-ooka commented May 8, 2024

https://leetcode.com/problems/group-anagrams/description/

Description

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.

(Nは要素数、Kは文字列の最大文字数)

#### メモ
- Hashmapの初期値をListにする方法が出てこなかったため、時間内にPassできず。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getdefaultdictも知らないならどう書きますか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ヒントを頂いたように、以下のようにすでに値が存在しているか確認をして、なければ追加をする(カルテ作る)形になると思いました!

// hash = { 'a': [], 'b': [] }

if 'a' in hash:
  hash['a'].append("apple")
else:
  hash['a'] = ["apple"]

ans = {}

for s in strs:
arr = [0] * 26
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

26がmagic numberです。定数を定義するといいでしょう。arrという変数名をもっと分かりやすくするならどうしますか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

26を定数として定義するといいこと、わかりました!

arrについて、
使用用途が文字列に使用されている文字数のカウントアップなので、char_countsとかが適切であったかと思います。


#### 調べた解法
- Step1と同様にASCII値とListを使用した方法。
- ソートされた文字列をkeyとして使用する方法。(NKlogK for time comp, N for space comp)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

別解の方も試したてみたらいいかと思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

step-2-1.pyに別解のコーディングも入れてみました!

@t-ooka
Copy link
Copy Markdown
Owner Author

t-ooka commented Jun 14, 2024

しばらく空けても解けたのでマージします。

@t-ooka t-ooka merged commit 78aeb61 into main Jun 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants