每天学习一点算法 2025/11/27
题目:字符串中的第一个唯一字符
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
-
找字符串中的某个字符的下标,我第一时间就想到
String.prototype.indexOf()那么我们怎么确定是否是唯一的呢?我又想到
String.prototype.lastIndexOf()我们直接遍历字符串判断他的
lastIndex和 index 是否相等,这不就可以判断她是否是唯一的了吗。function firstUniqChar(s: string): number { for (let i = 0; i < s.length; i++) { if (s.indexOf(s[i]) === s.lastIndexOf(s[i])) { return i } } return -1 }; -
通用解法的话就是用哈希表,使用Map统计出字符串中每个字符出现的次数,然后再次遍历找出第一个次数为一的字符。
function firstUniqChar(s: string): number { const frequency = new Map() for (let i = 0; i < s.length; i++) { const char = s[i] if (frequency.has(char)) { frequency.set(char, frequency.get(char) + 1) } else { frequency.set(char, 1) } } for (let i = 0; i < s.length; i++) { if (frequency.get(s[i]) === 1) return i } return -1 };
题目来源:力扣(LeetCode)

被折叠的 条评论
为什么被折叠?



