logo

Trie Data Structure | Vložiť a vyhľadať

The Vyskúšajte štruktúru údajov je stromová dátová štruktúra používaná na ukladanie dynamickej množiny reťazcov. Bežne sa používa na efektívne získavanie a skladovanie kľúčov vo veľkom súbore údajov. Konštrukcia podporuje operácie ako napr vkladanie , Vyhľadávanie , a vymazanie kľúčov, vďaka čomu je cenným nástrojom v oblastiach ako počítačová veda a vyhľadávanie informácií. V tomto článku budeme skúmať vkladanie a vyhľadávanie operácie v dátovej štruktúre Trie.

Vyskúšajte štruktúru údajov

Vyskúšajte štruktúru údajov



Obsah

  • Zastúpenie Trie Node
  • Zastúpenie Trie Node:

    A Vyskúšajte štruktúru údajov pozostáva z uzlov spojených hranami. Každý uzol predstavuje znak alebo časť reťazca. Koreňový uzol, začiatočný bod Trie, predstavuje prázdny reťazec. Každá hrana vychádzajúca z uzla znamená špecifický znak. Cesta od koreňa k uzlu predstavuje predponu reťazca uloženého v Trie.

    Jednoduchá štruktúra reprezentujúca uzly anglickej abecedy môže byť nasledovná.



    vba
    C++
    struct TrieNode {  // pointer array for child nodes of each node  TrieNode* childNode[26];  // Used for indicating ending of string  bool wordEnd;  TrieNode()  {  // constructor  // initialize the wordEnd variable with false  // initialize every index of childNode array with  // NULL  wordEnd = false;  for (int i = 0; i < 26; i++) {  childNode[i] = NULL;  }  } };>
    Java
    public class TrieNode {    // Array for child nodes of each node  TrieNode[] childNode;    // Used for indicating the end of a string  boolean wordEnd;  // Constructor  public TrieNode() {  // Initialize the wordEnd variable with false  wordEnd = false;  // Initialize every index of the childNode array with null  childNode = new TrieNode[26];  for (int i = 0; i < 26; i++) {  childNode[i] = null;  }  } }>

    Poďme si prejsť procesom vkladania slov do dátovej štruktúry Trie. Už sme pokryli základy Trie a jeho štruktúru uzlov.

    algoritmus triedenia vloženia

    Tu je vizuálna reprezentácia vkladania slov a a na do dátovej štruktúry Tri:




    Vložiť operáciu do Trie Data Structure


    Vkladanie a v dátovej štruktúre Tri:

    java lambda
    • Začnite v koreňovom uzle: Koreňový uzol nemá s ním spojený žiadny znak wordEnd hodnota je 0 , čo znamená, že v tomto bode nie je ukončené žiadne celé slovo.
    • Prvý znak a: Vypočítajte index pomocou „ a’ – ‘a’ = 0 . Skontrolujte, či childNode[0] je nulový . Keďže je, vytvorte nový TrieNode s postavou a , wordEnd nastavený na 0 a prázdne pole ukazovateľov. Presuňte sa do tohto nového uzla.
    • Druhý znak n: Vypočítajte index pomocou „n“ – „a“ = 13 . Skontrolujte, či childNode[13] je nulový . Je, takže vytvorte nový TrieNode s postavou n , wordEnd nastavený na 0 a prázdne pole ukazovateľov. Presuňte sa do tohto nového uzla.
    • Tretí znak d: Vypočítajte index pomocou „ d“ – „a“ = 3 . Skontrolujte, či childNode[3 ] je nulový . Je, takže vytvorte nový TrieNode s postavou d , wordEnd nastavený na 1 (označenie slova a tu končí).

    Vloženie mravca do dátovej štruktúry Trie:

    • Začnite v koreňovom uzle: Koreňový uzol neobsahuje žiadne údaje, ale sleduje každý prvý znak každého reťazca, ktorý bol vložený.
    • Prvý znak a: Vypočítajte index pomocou „ a’ – ‘a’ = 0 . Skontrolujte, či childNode[0] je nulový . Už máme a uzol vytvorený z predchádzajúceho vloženia. tak sa presuňte do existujúceho a uzol.
    • Prvý znak n: Vypočítajte index pomocou „ n’ – ‘a’ = 13 . Skontrolujte, či childNode [13] je nulový . Nie je, takže prejdite na existujúce n uzol.
    • Druhý znak t: Vypočítajte index pomocou „t“ – „a“ = 19 . Skontrolujte, či childNode [19] je nulový . Je, takže vytvorte nový TrieNode s postavou t , wordEnd nastavený na 1 (tu končí slovo mravec).

    Nižšie je uvedená implementácia vkladania reťazcov v dátovej štruktúre Trie:

    C++
    #include  using namespace std; struct TrieNode {  // pointer array for child nodes of each node  TrieNode* childNode[26];  // Used for indicating ending of string  bool wordEnd;  TrieNode()  {  // constructor  // initialize the wordEnd variable with false  // initialize every index of childNode array with  // NULL  wordEnd = false;  for (int i = 0; i < 26; i++) {  childNode[i] = NULL;  }  } }; void insert_key(TrieNode* root, string& key) {  // Initialize the currentNode pointer  // with the root node  TrieNode* currentNode = root;  // Iterate across the length of the string  for (auto c : key) {  // Check if the node exist for the current  // character in the Trie.  if (currentNode->childNode[c - 'a'] == NULL) { // Ak uzol pre aktuálny znak neexistuje // potom vytvorte nový uzol TrieNode* newNode = new TrieNode();  // Ponechajte referenciu pre novovytvorený // uzol.  currentNode->childNode[c - 'a'] = newNode;  } // Teraz presuňte ukazovateľ aktuálneho uzla na novo // vytvorený uzol.  currentNode = currentNode->childNode[c - 'a'];  } // Zvýšte počet wordEndCount pre posledný ukazovateľ currentNode // to znamená, že existuje reťazec končiaci na // currentNode.  currentNode->wordEnd = 1; }>

    Časová zložitosť: O(počet slov * maxLengthOfWord)
    Pomocný priestor: O(počet slov * maxLengthOfWord)

    Hľadanie kľúča v dátovej štruktúre Trie je podobné jeho operácii vkladania. Avšak iba To porovnáva postavy a posúva sa nadol . Vyhľadávanie sa môže ukončiť v dôsledku konca reťazca alebo nedostatku kľúča v pokuse.

    Postupný prístup k vyhľadávaniu v štruktúre údajov Trie:

    • Začnite v koreňovom uzle. Toto je východiskový bod pre všetky vyhľadávania v Trie.
    • Prejdite Trie na základe znakov slova, ktoré hľadáte. Pre každú postavu postupujte podľa príslušnej vetvy v Trie. Ak vetva neexistuje, slovo sa v Trie nenachádza.
    • Ak sa dostanete na koniec slova a príznak wordEnd je nastavený na 1, slovo bolo nájdené.
    • Ak sa dostanete na koniec slova a príznak wordEnd je 0, slovo sa v Trie nenachádza, aj keď zdieľa predponu s existujúcim slovom.

    Tu je vizuálna reprezentácia hľadaného slova ocko v dátovej štruktúre Tri:

    Predpokladajme, že sme slová úspešne vložili a , na , a ocko do nášho Trie a musíme hľadať konkrétne slová v dátovej štruktúre Trie. Skúsme vyhľadať slovo ocko :


    css zmena veľkosti obrázka

    Operácia vyhľadávania v štruktúre údajov Trie


    • Začíname pri koreňovom uzle.
    • Sledujeme vetvu zodpovedajúcu znaku ‚d‘.
    • Sledujeme vetvu zodpovedajúcu znaku a’.
    • Sledujeme vetvu zodpovedajúcu znaku ‚d‘.
    • Dostávame sa na koniec slova a wordEnd vlajka je 1 . To znamená, že ocko je prítomný v Trie.

    Nižšie je uvedená implementácia vyhľadávacích reťazcov v štruktúre údajov Trie:

    C++
    #include  using namespace std; struct TrieNode {  // pointer array for child nodes of each node  TrieNode* childNode[26];  // Used for indicating ending of string  bool wordEnd;  TrieNode()  {  // constructor  // initialize the wordEnd variable with false  // initialize every index of childNode array with  // NULL  wordEnd = false;  for (int i = 0; i < 26; i++) {  childNode[i] = NULL;  }  } }; bool search_key(TrieNode* root, string& key) {  // Initialize the currentNode pointer  // with the root node  TrieNode* currentNode = root;  // Iterate across the length of the string  for (auto c : key) {  // Check if the node exist for the current  // character in the Trie.  if (currentNode->childNode[c - 'a'] == NULL) { // Dané slovo v Trie neexistuje return false;  } // Presuňte ukazovateľ currentNode na už // existujúci uzol pre aktuálny znak.  currentNode = currentNode->childNode[c - 'a'];  } return (currentNode->wordEnd == true); }>

    Časová zložitosť: O(počet slov * maxLengthOfWord)
    Pomocný priestor: O(počet slov * maxLengthOfWord)

    celé číslo na reťazec java

    Vytvorte koreňový uzol s pomocou TrieNode() konštruktér.

  • Uložte kolekciu reťazcov, ktoré sa majú vložiť do trie, do vektora reťazcov, povedzme, arr .
  • Vloženie všetkých reťazcov do Trie s pomocou vložiť_kľúč() funkcia,
  • Vyhľadávajte reťazce pomocou search_key() funkciu.

Nižšie je uvedená implementácia vyššie uvedeného prístupu:

C++
#include  using namespace std; struct TrieNode {  // pointer array for child nodes of each node  TrieNode* childNode[26];  // Used for indicating ending of string  bool wordEnd;  TrieNode()  {  // constructor  // initialize the wordEnd variable with false  // initialize every index of childNode array with  // NULL  wordEnd = false;  for (int i = 0; i < 26; i++) {  childNode[i] = NULL;  }  } }; void insert_key(TrieNode* root, string& key) {  // Initialize the currentNode pointer  // with the root node  TrieNode* currentNode = root;  // Iterate across the length of the string  for (auto c : key) {  // Check if the node exist for the current  // character in the Trie.  if (currentNode->childNode[c - 'a'] == NULL) { // Ak uzol pre aktuálny znak neexistuje // potom vytvorte nový uzol TrieNode* newNode = new TrieNode();  // Ponechajte referenciu pre novovytvorený // uzol.  currentNode->childNode[c - 'a'] = newNode;  } // Teraz presuňte ukazovateľ aktuálneho uzla na novo // vytvorený uzol.  currentNode = currentNode->childNode[c - 'a'];  } // Zvýšte počet wordEndCount pre posledný ukazovateľ currentNode // to znamená, že existuje reťazec končiaci na // currentNode.  currentNode->wordEnd = 1; } bool search_key(TrieNode* root, string& key) { // Inicializácia ukazovateľa currentNode // s koreňovým uzlom TrieNode* currentNode = root;  // Iterácia cez dĺžku reťazca for (auto c : key) { // Skontrolujte, či existuje uzol pre aktuálny znak // v Trie.  if (currentNode->childNode[c - 'a'] == NULL) { // Dané slovo v Trie neexistuje return false;  } // Presuňte ukazovateľ currentNode na už // existujúci uzol pre aktuálny znak.  currentNode = currentNode->childNode[c - 'a'];  } return (currentNode->wordEnd == true); } // Kód ovládača int main() { // Vytvorenie koreňového uzla pre Trie TrieNode* root = new TrieNode();  // Uloží reťazce, ktoré chceme vložiť do // Trie vektorainputStrings = { 'and', 'ant', 'do', 'geek', 'otec', 'ball' };  // počet operácií vloženia v Trie int n = inputStrings.size();  pre (int i = 0; i< n; i++) {  insert_key(root, inputStrings[i]);  }  // Stores the strings that we want to search in the Trie  vectorsearchQueryStrings = { 'do', 'geek', 'bat' };  // počet operácií vyhľadávania v Trie int searchQueries = searchQueryStrings.size();  pre (int i = 0; i< searchQueries; i++) {  cout << 'Query String: ' << searchQueryStrings[i]  << '
';  if (search_key(root, searchQueryStrings[i])) {  // the queryString is present in the Trie  cout << 'The query string is present in the '  'Trie
';  }  else {  // the queryString is not present in the Trie  cout << 'The query string is not present in '  'the Trie
';  }  }  return 0; }>
Java
class TrieNode {  TrieNode[] childNode;  boolean wordEnd;  TrieNode()  {  childNode = new TrieNode[26];  wordEnd = false;  } } class Trie {  TrieNode root;  Trie() { root = new TrieNode(); }  // Function to insert a key into the Trie  void insert(String key)  {  TrieNode currentNode = root;  for (int i = 0; i < key.length(); i++) {  int index = key.charAt(i) - 'a';  if (currentNode.childNode[index] == null) {  currentNode.childNode[index]  = new TrieNode();  }  currentNode = currentNode.childNode[index];  }  currentNode.wordEnd = true;  }  // Function to search for a key in the Trie  boolean search(String key)  {  TrieNode currentNode = root;  for (int i = 0; i < key.length(); i++) {  int index = key.charAt(i) - 'a';  if (currentNode.childNode[index] == null) {  return false;  }  currentNode = currentNode.childNode[index];  }  return currentNode.wordEnd;  } } public class Main {  public static void main(String[] args)  {  Trie trie = new Trie();  String[] inputStrings  = { 'and', 'ant', 'do', 'geek', 'dad', 'ball' };  // Insert each string into the Trie  for (String str : inputStrings) {  trie.insert(str);  }  String[] searchQueryStrings  = { 'do', 'geek', 'bat' };  // Search for each string and print whether it is  // found in the Trie  for (String query : searchQueryStrings) {  System.out.println('Query String: ' + query);  if (trie.search(query)) {  System.out.println(  'The query string is present in the Trie');  }  else {  System.out.println(  'The query string is not present in the Trie');  }  }  } }>
Python
class TrieNode: def __init__(self): self.childNode = [None] * 26 self.wordEnd = False class Trie: def __init__(self): self.root = TrieNode() # Function to insert a key into the Trie def insert(self, key): currentNode = self.root for char in key: index = ord(char) - ord('a') if not currentNode.childNode[index]: currentNode.childNode[index] = TrieNode() currentNode = currentNode.childNode[index] currentNode.wordEnd = True # Function to search for a key in the Trie def search(self, key): currentNode = self.root for char in key: index = ord(char) - ord('a') if not currentNode.childNode[index]: return False currentNode = currentNode.childNode[index] return currentNode.wordEnd if __name__ == '__main__': trie = Trie() inputStrings = ['and', 'ant', 'do', 'geek', 'dad', 'ball'] # Insert each string into the Trie for word in inputStrings: trie.insert(word) searchQueryStrings = ['do', 'geek', 'bat'] # Search for each string and print whether it is found in the Trie for query in searchQueryStrings: print('Query String:', query) if trie.search(query): print('The query string is present in the Trie') else: print('The query string is not present in the Trie')>
JavaScript
class TrieNode {  constructor() {  // Initialize the childNode array with 26 nulls  this.childNode = Array(26).fill(null);  // Initialize wordEnd to the false indicating that no word ends here yet  this.wordEnd = false;  } } class Trie {  constructor() {  // Initialize the root node of the Trie  this.root = new TrieNode();  }  // Function to insert a key into the Trie  insert(key) {  // Start from the root node  let currentNode = this.root;  for (let i = 0; i < key.length; i++) {  const index = key.charCodeAt(i) - 'a'.charCodeAt(0);  if (currentNode.childNode[index] === null) {  currentNode.childNode[index] = new TrieNode();  }  // Move to the next node in the Trie  currentNode = currentNode.childNode[index];  }  // Mark the end of the word  currentNode.wordEnd = true;  }  // Function to search for a key in the Trie  search(key) {  // Start from the root node  let currentNode = this.root;  // Iterate through each character in the key  for (let i = 0; i < key.length; i++) {  const index = key.charCodeAt(i) - 'a'.charCodeAt(0);  if (currentNode.childNode[index] === null) {  return false;  }  // Move to the next node in the Trie  currentNode = currentNode.childNode[index];  }  // Return true if the end of the word is marked otherwise false  return currentNode.wordEnd;  } } // Driver code const trie = new Trie(); const inputStrings = ['and', 'ant', 'do', 'geek', 'dad', 'ball']; // Insert each string into the Trie inputStrings.forEach((str) =>trie.insert(str)); const searchQueryStrings = ['do', 'geek', 'bat']; // Vyhľadajte každý reťazec a vytlačte, či sa nachádza v Trie searchQueryStrings.forEach((query) => { console.log(`Query String: ${query}`); if (trie.search(query)) { console.log('Reťazec dopytu je prítomný v Trie' } else { console.log('Reťazec dopytu nie je prítomný v Trie' } });>

Výkon
Query String: do The query string is present in the Trie Query String: geek The query string is present in the Trie Query String: bat The query string is not present in the Trie>

Skúste Odstrániť
  • Zobrazuje sa obsah Trie
  • Funkcia automatického dokončovania pomocou funkcie Trie
  • Vyhľadávanie vzorov pomocou Trie všetkých prípon
  • Problémy s praxou:

    • Minimálny zlom slov
    • Jedinečné riadky v binárnej matici
    • Počet odlišných podreťazcov
    • Slovo Boggle
    • Triedenie poľa reťazcov (alebo slov) pomocou Trie