当前位置:   article > 正文

Leetcode 387: 字符串中的第一个唯一的字符

Leetcode 387: 字符串中的第一个唯一的字符

题目描述:

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 

注意事项:您可以假定该字符串只包含小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
 

思路:遍历字符串,用对象或者map统计每个字符出现的次数,遍历对象,一旦出现次数为1的就返回该字符。

  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var firstUniqChar = function(s) {
  6. if(s.length === 0) return -1;
  7. let hash = {};
  8. let len = s.length;
  9. for(let i = 0; i < len; i++) {
  10. hash[s[i]] = hash[s[i]] ? hash[s[i]] + 1 : 1;
  11. }
  12. for(let j = 0; j < len; j++) {
  13. if(hash[s[j]] === 1) {
  14. return j;
  15. }
  16. }
  17. return -1;
  18. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/727451
推荐阅读
相关标签
  

闽ICP备14008679号