Re: [閒聊] 每日LeetCode已回收
看板Marginalman作者JerryChungYC (JerryChung)時間2年前 (2024/02/05 08:52)推噓2(2推 0噓 5→)留言7則, 4人參與討論串650/719 (看更多)
https://leetcode.com/problems/first-unique-character-in-a-string
387. First Unique Character in a String
給一個字串s,找到第一個不重複的字元回傳其索引,不存在則回傳-1
Example 1:
Input: s = "leetcode"
Output: 0
Example 2:
Input: s = "loveleetcode"
Outpue: 2
Example 3:
Input: s = "aabb"
Output: -1
思路:
用for迴圈找出只出現一次的字元
Python3 code:
----------------------------------------------------
class Solution:
def firstUniqChar(self, s: str) -> int:
for i, w in enumerate(s):
if s.count(w) == 1:
return i
return -1
----------------------------------------------------
簡單 快速 4448ms
https://i.imgur.com/ZvmHhKo.png

思路:
用Counter找出所有字元出現的次數,再回傳value第一個為1的
Python3 code:
----------------------------------------------------
class Solution:
def firstUniqChar(self, s: str) -> int:
counter = Counter(s)
if 1 not in counter.values(): return -1
for k, v in counter.items():
if v == 1:
return s.find(k)
----------------------------------------------------
https://i.imgur.com/1Wq3c52.png

上週連寫了5天 結果六日都沒寫 哈
就不會動態規劃((
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.251.109 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1707094335.A.61C.html
※ 編輯: JerryChungYC (125.227.251.109 臺灣), 02/05/2024 08:56:04
→
02/05 08:58,
2年前
, 1F
02/05 08:58, 1F
推
02/05 09:01,
2年前
, 2F
02/05 09:01, 2F
推
02/05 09:01,
2年前
, 3F
02/05 09:01, 3F
→
02/05 09:04,
2年前
, 4F
02/05 09:04, 4F
→
02/05 09:08,
2年前
, 5F
02/05 09:08, 5F
→
02/05 09:08,
2年前
, 6F
02/05 09:08, 6F
→
02/05 09:08,
2年前
, 7F
02/05 09:08, 7F
討論串 (同標題文章)
以下文章回應了本文 (最舊先):
完整討論串 (本文為第 650 之 719 篇):