※ 引述《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
}
}