FirstUniqueCharIndex
问题描述
给定一个字符串 s
,找到其中第一个不重复的字符并返回其索引。如果不存在,返回 -1
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type cases = [
Expect<Equal<FirstUniqueCharIndex<'leetcode'>, 0>>,
Expect<Equal<FirstUniqueCharIndex<'loveleetcode'>, 2>>,
Expect<Equal<FirstUniqueCharIndex<'aabb'>, -1>>,
Expect<Equal<FirstUniqueCharIndex<''>, -1>>,
Expect<Equal<FirstUniqueCharIndex<'aaa'>, -1>>,
]
// ============= Your Code Here =============
// 答案
type FirstUniqueCharIndex<
T extends string,
U extends string[] = []
> = T extends `${infer F}${infer R}`
// 判断F 在不在 U中存在相同的
? F extends U[number]
// 如果在就把F添加进去,此时也相当于索引+1了
? FirstUniqueCharIndex<R, [...U, F]>
// 如果不在,继续判断F在不在R中存在
: R extends `${string}${F}${string}`
? FirstUniqueCharIndex<R, [...U, F]>
// 双重判断后都不在,就可以返回索引了
: U['length']
: -1