TikTok 面试题 #4 —— 字符串第一个唯一字符|tiktok 面经|面试辅助指南

85次阅读
没有评论

A unique character is one that appears only once in a string.
Given a string consisting of lowercase English letters only, return the index of the first occurrence of a unique character in the string using 1-based indexing.
If the string does not contain any unique character, return -1.

Example:
s = "statistics"
The unique characters are [a, c], and a occurs first.
Using 1-based indexing, its index is 3.

Another Example:
Input: "hackthegame"
Unique characters: [c, k, t, g, m]
The character c occurs first at index 3.

这题让你从一个小写字母组成的字符串中,找到 第一个只出现一次的字符,并返回它的 1-based 下标(也就是从 1 开始算的位置)。

思路常用做法有两种:

  1. 哈希表计数(最推荐)
    • 扫一扫统计每个字符出现次数
    • 再从头扫描,找到第一个出现次数为 1 的字符
    • 返回下标 +1(因为 1-based)
  2. 有序字典(OrderedDict)(不如方法 1 通用)

时间复杂度:O(n)
空间复杂度:O(1)(因为字符集固定为 26 个小写字母)

若没有唯一字符,返回 -1

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Tiktok、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Tiktok 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0