Trie Estructura de dades | Insereix i cerca

Trie Estructura de dades | Insereix i cerca

El Proveu l'estructura de dades és una estructura de dades en forma d'arbre que s'utilitza per emmagatzemar un conjunt dinàmic de cadenes. S'utilitza habitualment per a eficient recuperació i emmagatzematge de claus en un conjunt de dades gran. L'estructura admet operacions com ara inserció , cerca , i supressió de claus, la qual cosa la converteix en una eina valuosa en camps com la informàtica i la recuperació d'informació. En aquest article anem a explorar inserció i cerca operació a Trie Data Structure.

Proveu l

Proveu l'estructura de dades

Taula de contingut

A continuació es mostra la implementació de l'enfocament anterior:

C++ childNode[c - 'a'] = nouNode; } // Ara, moveu el punter del node actual al // nou node creat. currentNode = currentNode->childNode[c - 'a']; } // Incrementa el wordEndCount per a l'últim punter currentNode // això implica que hi ha una cadena que acaba en // currentNode. currentNode->wordEnd = 1; } bool clau_cerca(TrieNode* arrel, cadena& clau) { // Inicialitzar el punter currentNode // amb el node arrel TrieNode* currentNode = arrel; // Recorre la longitud de la cadena per a (clau automàtica c :) { // Comproveu si existeix el node per al // caràcter actual del Trie. if (currentNode->childNode[c - 'a'] == NULL) { // La paraula donada no existeix a Trie retorna fals; } // Mou el punter currentNode al // node ja existent per al caràcter actual. currentNode = currentNode->childNode[c - 'a']; } retorn (currentNode->wordEnd == true); } // Codi del controlador int main() { // Crea un node arrel per a l'arrel Trie TrieNode* = new TrieNode(); // Emmagatzema les cadenes que volem inserir al // vector Trie inputStrings = { 'and', 'ant', 'do', 'geek', 'pare', 'ball'}; // nombre d'operacions d'inserció al Trie int n = inputStrings.size(); per (int i = 0; i < n; i++) { insert_key(root, inputStrings[i]); } // Stores the strings that we want to search in the Trie vector searchQueryStrings = { 'fer', 'friki', 'bat'}; // nombre d'operacions de cerca al Trie int searchQueries = searchQueryStrings.size(); per (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 = ['fer', 'friki', 'bat']; // Cerqueu cada cadena i imprimiu si es troba al Trie searchQueryStrings.forEach((query) => { console.log(`Query String: ${query}`); if (trie.search(query)) { console.log('La cadena de consulta està present al Trie' } else { console.log('La cadena de consulta no està present al Trie');>>>   
Sortida Articles relacionats:

  • Proveu de suprimir
  • Es mostra el contingut de Trie
  • Funció d'emplenament automàtic amb Trie
  • Cerca de patrons utilitzant una prova de tots els sufixos
  • Problemes de pràctica:

    • Descans de paraules mínim
    • Files úniques en una matriu binària
    • Recompte de subcadenes diferents
    • Word Boggle
    • Ordenació de matrius de cadenes (o paraules) amb Trie