Skip to main content

Leetcode - 387. First Unique Character in a String

· One min read

https://leetcode.com/problems/first-unique-character-in-a-string/

Solution 1

/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function (s) {
const hashMap = {};
for (let i = 0; i < s.length; i++) {
if (hashMap[s[i]]) {
hashMap[s[i]] = {
...hashMap[s[i]],
count: hashMap[s[i]].count + 1,
};
} else {
hashMap[s[i]] = {
index: i,
count: 1,
};
}
}

const filteredResult = Object.entries(hashMap)
.map(([key, value]) => {
if (value.count === 1) {
return value.index;
}
})
.filter((value) => value !== false && value !== undefined);

return filteredResult.length === 0 ? -1 : filteredResult[0];
};