Open
Conversation
shining-ai
reviewed
Feb 22, 2024
| def firstUniqChar(self, s: str) -> int: | ||
| freq = [0] * 26 | ||
| for c in s: | ||
| freq[ord(c) - ord('a')] += 1 |
There was a problem hiding this comment.
listを使った解法にしたんですね。
想定外の文字列が入ってたらエラーになるので、dictのほうが安全かつ分かりやすいと思いました。
今回は英アルファベット小文字のみの制約があるので、気にし過ぎたコメントかもしれません。
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます。
想定外の文字列が入ってたらエラーになるので、dictのほうが安全かつ分かりやすいと思いました。
まあ何を想定するかですかねー。英アルファベット小文字が来ることが担保できる状況ならハッシュ処理が入らない固定長のlistを使った方が早いと思ったのでlistの解法にしました。アルファベットをインデックス値に変換する処理が入るのでその分複雑にはなりますね。
dictは前提条件が変わって文字種が増えた際などにそのまま使い回せるので良いと思います。
Owner
Author
There was a problem hiding this comment.
半年後に読んだ別の同僚が不安にならないか、環境の変化に対して頑健か、なのです。
まあでもとりあえず書くならdictの方が良い気がしてきました。そのうえで入力値の制約下でパフォーマンスを向上させたいなどの要件があった際にlistを使った方を書く方がいいですね。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://leetcode.com/problems/first-unique-character-in-a-string/