Given a string,
find the first non-repeating character in it and return it's index.
If it doesn't exist, return -1.
input: 給一字串
output: 找出第一個沒有重覆的字元
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
};
如何解
丟入 Map 然後抓第一個 length = 1 的值 (Map 有順序性)
var firstUniqChar = function(s) {
let myMap = new Map();
for(let i = 0; i < s.length; i++){
if(myMap.has(s[i])){
myMap.set(s[i], myMap.get(s[i]) + 1)
}else{
myMap.set(s[i], 1)
}
}
for(let item of myMap){
if(item[1] == 1){
return s.indexOf(item[0])
}
}
return -1;
};
// // faster than 14.00% of JavaScript online submissions