Re: [閒聊] 每日LeetCode

作者: yam276 ('_')   2024-02-05 17:51:20
※ 引述《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
}
}
作者: wu10200512 (廷廷)   2024-02-05 17:52:00
跟我想的一樣有一個迴圈解決的方法嗎
作者: yam276 ('_')   2024-02-05 17:56:00
我有想過雙指針 但效率稀爛不用哈希表可以改建立26字長度陣列紀錄次數從效率上只能兩個for一個紀錄一個尋找 只有一個 會O(n^2)
作者: ILoveErr (英梨梨我老婆)   2024-02-05 18:09:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com