作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/ 来源:力扣(LeetCode)

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题目

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:

s = “leetcode”

返回 0

s = “loveleetcode”

返回 2

提示:你可以假定该字符串只包含小写字母。

相关标签
哈希表 字符串

题解

hashMap来记录每个字符出现的次数
在循环一次找出出现1次的字符索引

  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var firstUniqChar = function(s) {
  6. let map = new Map();
  7. let arr = s.split('');
  8. for (let x of arr) {
  9. let cur = map.get(x);
  10. if (cur) {
  11. map.set(x, cur+1);
  12. } else {
  13. map.set(x, 1);
  14. }
  15. }
  16. for (let i = 0; i < s.length; i++) {
  17. if (map.get(s[i]) === 1) {
  18. return i;
  19. }
  20. }
  21. return -1;
  22. };

参考:
https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/zi-fu-chuan-zhong-de-di-yi-ge-wei-yi-zi-x9rok/