LeetCode 387. 字符串中的第一个唯一字符

Posted by cody1991 on August 9, 2020

简单思路:这道题很简单,主要想想怎么降低时间复杂度和空间复杂度吧

387. 字符串中的第一个唯一字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function (s) {
  const map = {};
  for (let index = 0; index < s.length; index += 1) {
    const c = s[index];
    if (map[c] === undefined) map[c] = index;
    else map[c] = -1;
  }
  let result = Infinity;
  let flag = 0;
  for (let key in map) {
    if (map[key] != -1) {
      result = Math.min(result, map[key]);
      flag = 1;
    }
  }
  return flag ? result : -1;
};

console.log(firstUniqChar("cc"));