题目地址:地址
解题思路
主要是利用哈希表来进行存储的操作。官方题解中,给的方式包括三种:
- 用哈希表存储每个字符出现的次数,第二次遍历出现1次的字符,返回当前的索引;
- 用哈希表存储索引。如果哈希表中存在该字符,那么该字符的索引设置为-1,如果不存在,那么哈希表将当前的字符作为key,当前的索引作为value来存储;遍历哈希表,当前的值不为-1就返回,如果都是-1,那么直接返回-1
- 也可以利用队列的方式,来寻找
代码
var firstUniqChar2 = function(s) {const position = new Map();const n = s.length;for (let [i, ch] of Array.from(s).entries()) {if (position.has(ch)) {position.set(ch, -1);} else {position.set(ch, i);}}let first = n;for (let pos of position.values()) {if (pos !== -1 && pos < first) {first = pos;}}if (first === n) {first = -1;}return first;};
var firstUniqChar = function(s) {const position = new Map();const q = [];const n = s.length;for (let [i, ch] of Array.from(s).entries()) {if (!position.has(ch)) {position.set(ch, i);q.push([s[i], i]);} else {position.set(ch, -1);while (q.length && position.get(q[0][0]) === -1) {q.shift();}}}return q.length ? q[0][1] : -1;};
