/*
* @lc app=leetcode.cn id=387 lang=typescript
*
* [387] 字符串中的第一个唯一字符
*/
// @lc code=start
function firstUniqChar(s: string): number {}
// @lc code=end
- 时间复杂度:
- 空间复杂度:
function firstUniqChar(s: string): number {
const cache = new Map<string, number>()
for (let i = 0; i < s.length; i++) {
if (cache.has(s[i])) cache.set(s[i], Infinity)
else cache.set(s[i], i)
}
for (const [, i] of cache) {
if (i !== Infinity) return i
}
return -1
}
test.each([
{ input: { s: 'leetcode' }, output: 0 },
{ input: { s: 'loveleetcode' }, output: 2 },
])('input: s = $input.s', ({ input: { s }, output }) => {
expect(firstUniqChar(s)).toEqual(output)
})