wengzc / leetcode

Record the leetcode
1 stars 0 forks source link

387. 字符串中的第一个唯一字符 #189

Open wengzc opened 3 years ago

wengzc commented 3 years ago

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

 

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

 

提示:你可以假定该字符串只包含小写字母。

题目链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string

wengzc commented 3 years ago

思路分析:哈希集,Map

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function (s) {
    let len = s.length
    let map = new Map()
    for (let i = 0; i < len; i++) {
        if (!map.has(s[i])) {
            map.set(s[i], 1)
        } else {
            map.set(s[i], map.get(s[i]) + 1)
        }
    }
    for (let i = 0; i < len; i++) {
        if (map.get(s[i]) === 1) {
            return i
        }
    }
    return -1
};