题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
思路:用Map结构来存储结果,键名为字符,值为字符的索引。
在循环遍历中,判断Map结构中是否已经存在该字符,如果已经存在,就将该字符删除;如果不存在,就将该字符存入Map结构中。
循环结束,取出Map结构中所有的值(values),将第一个return。若Map结构为空,则return -1.
function FirstNotRepeatingChar(str) { // write code here let count = new Map() for(let i = 0; i < str.length;i++){ count.has(str[i])?count.delete(str[i]) : count.set(str[i],i) } if(count.size===0){ return -1 }else{ return [...count.values()][0] } } module.exports = { FirstNotRepeatingChar : FirstNotRepeatingChar };