← 返回完整题库
Typescript简单

实现下面的 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;
}

关键点

  1. 必须两趟:只扫一趟不知道后面是否还会出现该字符。
  2. 用 for...of 遍历按 code point,能正确处理 emoji 与代理对;str[i] 是 UTF-16 码元,可能把 emoji 拆开。
  3. 字符集只有小写字母时用数组计数代替 Map,更快更省内存。
  4. 用 Map 而非普通对象,避免 __proto__/constructor 等键名冲突。
  5. 没有结果返回 null / -1,类型明确,不要返回 undefined。
  6. 计数也可用 str.split('').reduce 实现,但可读性不如两趟循环。

复杂度

时间 O(n),空间 O(k)(k 为不同字符数)。

本题来自 计算机知识面试题库,共 921 道题。