/*
* @lc app=leetcode.cn id=676 lang=typescript
*
* [676] 实现一个魔法字典
*/
// @lc code=start
class MagicDictionary {
constructor() {}
buildDict(dictionary: string[]): void {}
search(searchWord: string): boolean {}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* var obj = new MagicDictionary()
* obj.buildDict(dictionary)
* var param_2 = obj.search(searchWord)
*/
// @lc code=end
class MagicDictionary {
private set = new Set<string>()
constructor() {}
buildDict(dictionary: string[]): void {
this.set = new Set(dictionary)
}
search(searchWord: string): boolean {
for (let i = 0; i < searchWord.length; i++) {
for (let j = 0; j < 26; j++) {
const ch = String.fromCharCode(j + 97)
if (ch === searchWord[i]) continue
const str = searchWord.slice(0, i) + ch + searchWord.slice(i + 1)
if (this.set.has(str)) return true
}
}
return false
}
}
test.each([
{
input: {
ops: ['MagicDictionary', 'buildDict', 'search', 'search', 'search', 'search'],
params: [[], [['hello', 'leetcode']], ['hello'], ['hhllo'], ['hell'], ['leetcoded']],
},
output: [null, null, false, true, false, false],
},
])('input: param = $input.param', ({ input: { ops, params }, output }) => {
const cls = new MagicDictionary()
const res: (boolean | null)[] = [null]
for (let i = 1; i < ops.length; i++) {
res.push(cls[ops[i] as 'search'](...(params[i] as [string])) ?? null)
}
expect(res).toEqual(output)
})