retrieve_suggestion
函数用于检查数组的下一个字母。
但是如何使用新函数检查该函数的下一个字母,但使用retreive_suggestion
。我怎么能检查"Mar"
的下一个字母是树?新结果将在current
。
var words = ["Maria", "Marzia", "Mary", "Marphy", "Michael"];
function build_trie(words) {
var trie = new Object;
for (var i = 0; i < words.length; i++) {
insert_word(trie, words[i]);
}
return trie;
}
function insert_word(trie, word) {
var letters = word.split("");
var current = trie;
for (var j = 0; j < letters.length; j++) {
var character = letters[j];
var position = current[character];
if (position == null) {
current = current[character] = j == letters.length - 1 ? 0 : {};
} else {
current = current[character];
}
}
}
function retrieve_suggestion(trie, search_string) {
var letters = search_string.split("");
var current = trie;
console.log(current);
for (var j = 0; j < letters.length; j++) {
var letter = letters[j];
// console.log(letter);
var position = current[letter];
// console.log(letter);
if (position == null) {
current = current[letter] = j == letters.length - 1 ? 0 : {};
} else {
current = current[letter];
}
}
var suggestions = [];
// console.log(suggestions);
if (current === 0) {
suggestions = search_string;
} else {
var next_letters = Object.keys(current);
console.log(next_letters);
var number_of_suggestions = next_letters.length;
for (var k = 0; k < number_of_suggestions; k++) {
suggestions.push(search_string + next_letters[k]);
//console.log(z);
}
}
return suggestions;
console.log(suggestions);
}
trie = build_trie(words);
console.log(retrieve_suggestion(trie, "Mar"));