字典树
Last updated
Last updated
var root = {
a: {
b: {
c: {
repeatNum: 1,
},
d: {
repeatNum: 1,
},
}
}
}var root = {
a: {
b: {
repeatNum: 1,
c: {
repeatNum: 2, // 注意这里加1了
},
d: {
repeatNum: 1,
}
},
c: {
repeatNum: 1,
}
},
h: {
e: {
repeatNum: 1,
},
}
}// 字典树对象
class Trie {
constructor() {
this.$ = Symbol('$') // 用来记录字符串重复次数
this.root = Object.create(null) // 字典树本树
}
// 插入一个字符串
insert(str) {
let node = this.root, $ = this.$
for (let chat of str) {
if (!node[chat]) {
node[chat] = {}
}
// 每一次循环后,node都会被赋值为字母的对象,算是递归
node = node[chat]
}
if (!node[$]) node[$] = 0
node[$]++
}
// 获取重复次数最多的字符串和重复次数
most() {
let max = 0, str = '', $ = this.$
getMost(this.root, '')
return { max, str }
// 深度优先, 不停的拼接出原字符串,并拿到重复次数,和记录值 max 和 str 比较
function getMost(obj, lastStr) {
if (max < obj[$]) {
max = obj[$]
str = lastStr
}
for (let key in obj) {
getMost(obj[key], lastStr + key)
}
}
}
}
let trie = new Trie(), number = 100000
// 插入 number 条字符串
for (let i = 0; i < 100000; i++) {
let str = ''
for (let j = 0; j < 4; j++) {
str += String.fromCharCode(Math.floor(Math.random() * 26) + 'a'.charCodeAt(0))
}
trie.insert(str)
}
// 获取重复数最多的字符串信息
let mostObj = trie.most()
console.log('root: ', trie.root)
console.log('单词数量: ', number)
console.log('重复最多的单词: ', mostObj.str)
console.log('重复次数: ', mostObj.max)