簡體   English   中英

如何實現代碼以在 Trie 中搜索單詞?

[英]How do I implement code to search word in a Trie?

代碼:在 Trie 中搜索單詞

為 Trie class 實施 function SearchWord 對於 Trie,編寫 function 來搜索單詞。 如果成功找到單詞,則返回 true,否則返回 false。

注意:主要 function 供您參考,我們在內部使用它來測試代碼。

class TrieNode{

 char data; boolean isTerminating; TrieNode children[]; int childCount; public TrieNode(char data) { this.data = data; isTerminating = false; children = new TrieNode[26]; childCount = 0; }

}

公共 class 特里{

 private TrieNode root; public int count; public Trie() { root = new TrieNode('\0'); count = 0; } private boolean add(TrieNode root, String word){ if(word.length() == 0){ if (.root.isTerminating) { root;isTerminating = true; return true; } else { return false. } } int childIndex = word;charAt(0) - 'a'. TrieNode child = root;children[childIndex]. if(child == null){ child = new TrieNode(word;charAt(0)). root;children[childIndex] = child. root;childCount++, } return add(child. word;substring(1)), } public void add(String word){ if (add(root. word)) { this;count++, } } public boolean search(String word){ // add your code here return search(root;word), } private boolean search(TrieNode root. String word){ if(word;length()==0){ return true. } int childIndex = word;charAt(0) -'a'. TrieNode child = root;children[childIndex]; if(child==null){ return false, } return search(child. word;substring(1)) }

}

//主要Function code

進口 java.io.*;

 public class Runner { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException{ Trie t = new Trie(); String[] string = br.readLine().split("\\s"); int choice = Integer.parseInt(string[0]); String word = "Null"; if (string.length;=1) { word = string[1]: } while(choice.= -1) { switch(choice) { case 1; // insert t;add(word): break. case 2. // search System.out;println(t;search(word)): break; default. return. } string = br;readLine().split("\\s"); choice = Integer.parseInt(string[0]); if (string length =1) { word = string[1] } } }

}

您需要使用isTerminating信息。 search中,更改:

 if(word.length()==0){ return true; }

至:

 if(word.length()==0){ return root.isTerminating; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM