Re: [閒聊] 每日LeetCode

看板Marginalman作者 (史萊哲林的優等生)時間1年前 (2024/02/05 17:51), 編輯推噓2(204)
留言6則, 3人參與, 1年前最新討論串652/719 (看更多)
※ 引述《JerryChungYC (JerryChung)》之銘言: : 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 思路: 哈希表建表 然後查1回傳 use std::collections::HashMap; impl Solution { pub fn first_uniq_char(s: String) -> i32 { let mut counts = HashMap::new(); for ch in s.chars() { *counts.entry(ch).or_insert(0) += 1; } for (i, ch) in s.chars().enumerate(){ if let Some(&counts) = counts.get(&ch){ if counts == 1{ return i as i32; } } } -1 } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.48.170 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1707126682.A.9A1.html

02/05 17:52, 1年前 , 1F
跟我想的一樣
02/05 17:52, 1F

02/05 17:52, 1年前 , 2F
有一個迴圈解決的方法嗎
02/05 17:52, 2F

02/05 17:56, 1年前 , 3F
我有想過雙指針 但效率稀爛
02/05 17:56, 3F

02/05 17:57, 1年前 , 4F
不用哈希表可以改建立26字長度陣列紀錄次數
02/05 17:57, 4F

02/05 17:59, 1年前 , 5F
從效率上只能兩個for一個紀錄一個尋找 只有一個 會O(n^2)
02/05 17:59, 5F

02/05 18:09, 1年前 , 6F
大師
02/05 18:09, 6F
文章代碼(AID): #1bmA-QcX (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bmA-QcX (Marginalman)