ด้านล่างนี้คือโค้ดที่ใช้งาน HashMap ของ Trie แต่ฉันไม่แน่ใจว่าจะใช้ส่วนเติมข้อความอัตโนมัติได้อย่างไร ฉันเห็นว่าผู้คนใช้ LinkedList เพื่อใช้งาน Trie อย่างไร แต่ฉันต้องการที่จะเข้าใจด้วย HashMap ความช่วยเหลือใด ๆ ที่ชื่นชม ฉันได้วางโค้ดด้านล่างสำหรับ Trie ของฉันแล้ว
มีวิธีค้นหาคำนำหน้า จากนั้นไปที่ส่วนท้ายของคำนำหน้าแล้วค้นหาลูกๆ ของมันแล้วส่งคืนเป็นสตริงหรือไม่ และถ้าเป็นเช่นนั้น จะใช้งาน HashMap ได้อย่างไร หรือฉันไม่ควรทำสิ่งนี้ด้วย HashMap และไปที่ LinkedList และฉันไม่แน่ใจว่าทำไมอันหนึ่งถึงดีกว่าอันอื่น?
public class TrieNode {
Map<Character, TrieNode> children;
boolean isEndOfWord;
public TrieNode() {
isEndOfWord = false;
children = new HashMap<>();
}
}
public class TrieImpl {
private TrieNode root;
public TrieImpl() {
root = new TrieNode();
}
// iterative insertion into Trie Data Structure
public void insert(String word) {
if (searchTrie(word))
return;
TrieNode current = root;
for(int i=0; i<word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if(node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.isEndOfWord = true;
}
// search iteratively
public boolean searchTrie(String word) {
TrieNode current = root;
for(int i=0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if(node == null) {
return false;
}
current = node;
}
return current.isEndOfWord;
}
// delete a word recursively
private boolean deleteRecursive(TrieNode current, String word, int index) {
if(index == word.length()) {
if(!current.isEndOfWord) {
return false;
}
current.isEndOfWord = false;
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if(node == null) {
return false;
}
boolean shouldDeleteCurrentNode = deleteRecursive(node, word, index+1);
if(shouldDeleteCurrentNode) {
current.children.remove(ch);
return current.children.size() == 0;
}
return false;
}
// calling the deleteRecursively function
public boolean deleteRecursive(String word) {
return deleteRecursive(root, word, 0);
}
public static void main(String[] args) {
TrieImpl obj = new TrieImpl();
obj.insert("amazon");
obj.insert("amazon prime");
obj.insert("amazing");
obj.insert("amazing spider man");
obj.insert("amazed");
obj.insert("alibaba");
obj.insert("ali express");
obj.insert("ebay");
obj.insert("walmart");
boolean isExists = obj.searchTrie("amazing spider man");
System.out.println(isExists);
}
}