Question:
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Example:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Solution:
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
for (let i in s) {
if (s.indexOf(s[i]) === s.lastIndexOf(s[i])){
return i;
}
}
return -1;
};
Runtime: 228 ms, faster than 6.39% of JavaScript online submissions for First Unique Character in a String.
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
const obj = {}
for (let i in s) {
if(!obj[s[i]]) obj[s[i]] = 0;
obj[s[i]]++;
}
for (let j in s) {
if(obj[s[j]] === 1) {
return j;
}
}
return -1;
};
Runtime: 252 ms, faster than 5.51% of JavaScript online submissions for First Unique Character in a String