Skip to content

387. First Unique Character in a String#15

Open
tarinaihitori wants to merge 1 commit intomainfrom
307-first-unique-character-in-a-string
Open

387. First Unique Character in a String#15
tarinaihitori wants to merge 1 commit intomainfrom
307-first-unique-character-in-a-string

Conversation

@tarinaihitori
Copy link
Copy Markdown
Owner

s = "a\u0308" # 'a' + '̈'
print(s) # 出力: ä
print(len(s)) # 出力: 2
```
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ご存知かもしれませんが、同じウムラウト付きの文字でも、1文字のもの "ä" ("\u00e4") があります。
unicodedata.normalize を見ておくといいかもしれません。

unicodedata.normalize("NFC", "が")
'が'
len(unicodedata.normalize("NFC", "が"))
1
unicodedata.normalize("NFD", "が")
'が'
len(unicodedata.normalize("NFD", "が"))
2

return -1
```

Counter を使用した版
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

https://docs.python.org/3/library/collections.html#collections.Counter
挿入順番が保存されるようになったのは3.7からですね。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

linked list + hashmap という Java の LinkedHashMap や LRU などで用いられる構造なので、どこかで一回書いておいてください。
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html

とてもよく聞かれます。
https://discord.com/channels/1084280443945353267/1200089668901937312/1206182044292485171

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.

ありがとうございます。step4で書いてみます。


辞書ではなくリストを使った版
この場合、配列を使用しているので、インデックスによるアクセスにより、辞書よりも早くなる可能性がある。
その一方で、(制約では英小文字しかこないが)英小文字以外の文字が来ることも考えると辞書のほうが安全。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

英小文字でないものが来たときに、このコードだとどうなるか、その振る舞いでいいのかはちょっと考えてみましょう。

for char in s:
if char not in char_to_counts:
char_to_counts[char] = 0
char_to_counts[char] += 1
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

最終的にchar_to_countsの取得をこの方法で行ったのはなぜですか?Counterを使う方法が一番簡潔で、defaultdictを使うと条件分岐が要らなくなるので自分だったらその二つのいずれかを使うと思いました。

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.

3 participants