387.字符串中的第一个唯一字符
/**
* 给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
* @param {string} s
* @return {number}
*/
var firstUniqChar = function (s) {
let arr = s.split('')
let countMap = {}
for (let i = 0; i < arr.length; i++) {
let item = arr[i]
if (countMap[item] !== undefined) {
countMap[item].push(i)
} else {
countMap[item] = [i]
}
}
let indexes = Object.values(countMap)
.filter(e => e.length === 1)
.reduce((pre, next) => {
return [...pre, ...next]
}, [])
console.log(indexes);
if (indexes.length > 0) {
return Math.min(...indexes)
} else {
return -1
}
};
// 示例 1:
// 输入: s = "leetcode"
// 输出: 0
// console.log(firstUniqChar("leetcode"))
console.log(firstUniqChar("aadadaad"))