Re: [閒聊] 每日LeetCode
※ 引述《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
02/05 17:57, 4F
→
02/05 17:59,
1年前
, 5F
02/05 17:59, 5F
推
02/05 18:09,
1年前
, 6F
02/05 18:09, 6F
討論串 (同標題文章)