赞
踩
题目描述:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
思路:遍历字符串,用对象或者map统计每个字符出现的次数,遍历对象,一旦出现次数为1的就返回该字符。
- /**
- * @param {string} s
- * @return {number}
- */
- var firstUniqChar = function(s) {
- if(s.length === 0) return -1;
- let hash = {};
- let len = s.length;
- for(let i = 0; i < len; i++) {
- hash[s[i]] = hash[s[i]] ? hash[s[i]] + 1 : 1;
- }
- for(let j = 0; j < len; j++) {
- if(hash[s[j]] === 1) {
- return j;
- }
- }
- return -1;
- };

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。