Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions arai60/first_unique_character_in_a_string/phase1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Solution:
def firstUniqChar(self, s: str) -> int:
# 登場回数を数える
count_appearance = [0 for _ in range(128)]
for char in s:
count_appearance[ord(char)] += 1

for index, char in enumerate(s):
if count_appearance[ord(char)] == 1:
return index
return -1
35 changes: 35 additions & 0 deletions arai60/first_unique_character_in_a_string/phase2.py
Copy link

@seal-azarashi seal-azarashi Aug 5, 2024

Choose a reason for hiding this comment

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

ファイル末尾の空白行はあったほうがいいと思います

Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
reference
Exzrgsさん: https://github.com/Exzrgs/LeetCode/pull/9/files 命名を参考にした
hayashi-ayさん: https://github.com/hayashi-ay/leetcode/pull/28/files
2回ループをどうにか1回ループで回せないか考えてみたが, 1回ループでまわしたあと, 辞書が順序を保存することを使わないとうまく書けないことと, 少し複雑な条件分岐が入ることを学んだ

一応, 辞書を使っている人が多いのでdictを使うようにした。入力の文字列の名前がsなのでcharもcにした
"""
class Solution:
def firstUniqChar(self, s: str) -> int:
char_to_appear_count = defaultdict(int)
for c in s:
char_to_appear_count[c] += 1

for index, c in enumerate(s):
if char_to_appear_count[c] == 1:
return index
return -1

# ループを一回に済ませる
class Solution:
def firstUniqChar(self, s: str) -> int:
char_to_first_appear_index = defaultdict(int)
duplicated = set()
for index, c in enumerate(s):
if c in duplicated:
continue
if c in char_to_first_appear_index:
del char_to_first_appear_index[c]
duplicated.add(c)
continue
char_to_first_appear_index[c] = index
if not char_to_first_appear_index:
return -1
return next(iter(char_to_first_appear_index.values()))
10 changes: 10 additions & 0 deletions arai60/first_unique_character_in_a_string/phase3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Solution:
def firstUniqChar(self, s: str) -> int:
char_to_appear_count = defaultdict(int)
for c in s:
char_to_appear_count[c] += 1

for index, c in enumerate(s):
if char_to_appear_count[c] == 1:
return index
return -1