精華區beta Marginalman 關於我們 聯絡資訊
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
JIWP: 大師 02/05 08:58
PyTorch: 大師 02/05 09:01
wu10200512: 這不是哈希表ㄇ 02/05 09:01
JerryChungYC: 那就自己建 counter = {} :( 02/05 09:04
JerryChungYC: counter = defaultdict(int) 02/05 09:08
JerryChungYC: for i in s: 02/05 09:08
JerryChungYC: counter[i] += 1 02/05 09:08