Skip to content
On this page

387. First Unique Character in a String share

Problem Statement

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Solution:

rs
impl Solution {
    pub fn first_uniq_char(s: String) -> i32 {
        let mut map = std::collections::HashMap::new();
        for c in s.chars() {
            // increase the count of the character if exists
            // otherwise insert the character w/ default value 0
            // then increase the count by 1
            *map.entry(c).or_insert(0) += 1;
        }

        // iterate over the string and return the index of the first character
        // that has a count of 1
        for (i, c) in s.chars().enumerate() {
            if *map.get(&c).unwrap() == 1 {
                return i as i32;
            }
        }

        -1
    }
}

...


Released under the MIT License.