实现下面的 firstSingleChar 方法
参考答案
题目意图
找字符串中第一个只出现一次的字符。
实现(两趟 + Map 计数)
function firstSingleChar(str: string): string | null {
const count = new Map<string, number>();
for (const ch of str) count.set(ch, (count.get(ch) ?? 0) + 1);
for (const ch of str) if (count.get(ch) === 1) return ch;
return null;
}
返回索引版本
function firstSingleCharIndex(str: string): number {
const count = new Map<string, number>();
for (const ch of str) count.set(ch, (count.get(ch) ?? 0) + 1);
for (let i = 0; i < str.length; i++) {
if (count.get(str[i]) === 1) return i;
}
return -1;
}
关键点
- 必须两趟:只扫一趟不知道后面是否还会出现该字符。
- 用
for...of遍历按 code point,能正确处理 emoji 与代理对;str[i]是 UTF-16 码元,可能把 emoji 拆开。 - 字符集只有小写字母时用数组计数代替
Map,更快更省内存。 - 用
Map而非普通对象,避免__proto__/constructor等键名冲突。 - 没有结果返回
null/-1,类型明确,不要返回undefined。 - 计数也可用
str.split('').reduce实现,但可读性不如两趟循环。
复杂度
时间 O(n),空间 O(k)(k 为不同字符数)。