作者yam276 (史萊哲林的優等生)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Mon Feb 5 17:51:20 2024
※ 引述《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
推 wu10200512: 跟我想的一樣 02/05 17:52
→ wu10200512: 有一個迴圈解決的方法嗎 02/05 17:52
→ yam276: 我有想過雙指針 但效率稀爛 02/05 17:56
→ yam276: 不用哈希表可以改建立26字長度陣列紀錄次數 02/05 17:57
→ yam276: 從效率上只能兩個for一個紀錄一個尋找 只有一個 會O(n^2) 02/05 17:59
推 ILoveErr: 大師 02/05 18:09