diff --git a/60 LeetCode problems to solve for coding interview.xlsx b/60 LeetCode problems to solve for coding interview.xlsx index 1fa83ad..be5eaa8 100644 Binary files a/60 LeetCode problems to solve for coding interview.xlsx and b/60 LeetCode problems to solve for coding interview.xlsx differ diff --git a/lc387.md b/lc387.md new file mode 100644 index 0000000..ab7bd73 --- /dev/null +++ b/lc387.md @@ -0,0 +1,69 @@ +# step1 +思考ログ +- 2つのpointerを使って走査すれば最悪計算時間はO(n^2)かかるが単純だと思った. + +```python +class Solution: + def firstUniqChar(self, s: str) -> int: + seen = set() + for i in range(len(s)): + if s[i] in seen: + continue + j = i + 1 + is_repeat = False + while(j < len(s)): + if s[j] == s[i]: + is_repeat = True + j += 1 + + if is_repeat is False: + return i + seen.add(s[i]) + + return -1 +``` + +# step2 +- step1をchatgptに投げた結果, if s[j] == s[i]:のあとにbreakを入れるべきという指摘を受けた. その通りだと思った. +参考にした他の方のPR +- https://github.com/potrue/leetcode/pull/15/files?short_path=5e4287a#diff-5e4287a02e3f11dbbbe1217cb91b9370bcf7798cdde8ce6e7c1729817e53c0fc +- 前回同様,私のstep1での実装をライブラリ(Counterとfind)で簡潔に解いている実装だった.明らかにこちらの方が読みやすい. +```python +class Solution: + def firstUniqChar(self, s: str) -> int: + str_to_count = Counter(s) + for character in s: + if str_to_count[character] == 1: + return s.find(character) + + return -1 +``` +- enumerateで場所を特定する方法 +```python +class Solution: + def firstUniqChar(self, s: str) -> int: + str_to_count = Counter(s) + for i, character in enumerate(s): + if str_to_count[character] == 1: + return i + + return -1 +``` +- https://github.com/nktr-cp/leetcode/pull/16/files?short_path=0c860cd#diff-0c860cd754249868513e4f9054206317fa33d0f548fc3896ac2b3e11822fd852 +- c++での実装、ただ眺めていた + +- https://github.com/mura0086/arai60/pull/19/files#diff-5ec7c3c87171edf4d61e9eb79fd926cafa27caf068da7474222897c8e9e7ab96 +- [lru_cache](https://docs.python.org/ja/3.13/library/functools.html#functools.lru_cache)(Least Recently Used cache)という概念を初めて知った. + +# step3 +``` +class Solution: + def firstUniqChar(self, s: str) -> int: + char_to_count = Counter(s) + + for i, character in enumerate(s): + if char_to_count[character] == 1: + return i + + return -1 +```