当前位置:网站首页>LeetCode:387. The first unique character in the string

LeetCode:387. The first unique character in the string

2022-07-06 08:51:00 Bertil

Given a string s , find Its first non repeating character , And return its index . If it doesn't exist , Then return to -1 .

Example 1:

 Input : s = "leetcode"
 Output : 0

Example 2:

 Input : s = "loveleetcode"
 Output : 2

Example 3:

 Input : s = "aabb"
 Output : -1

Tips :

  • 1 <= s.length <= 10^5
  • s Contains only lowercase letters

Their thinking

1. First, use a hash table to count the number of times each letter appears
2. Then iterate through the string , If a character is found to appear only once , Directly return the corresponding subscript , Otherwise, return after the loop ends -1

Code

/** * @param {string} s * @return {number} */
var firstUniqChar = function(s) {
    
    //  Create a hash table 
    let map = new Map()
    //  Count the times 
    for (let i = 0; i < s.length; i++) {
    
        let word = s.charAt(i)
        if (map.has(word)) {
    
            let val = map.get(word)
            map.set(word, val + 1)
        } else {
    
            map.set(word, 1)
        }
    }
    //  Find the first letter that appears only once 
    for (let i = 0; i < s.length; i++) {
    
        if (map.get(s.charAt(i)) === 1) {
    
            return i
        }
    }
    return -1
};
原网站

版权声明
本文为[Bertil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060844308588.html