Trie duomenų struktūra | Įterpti ir ieškoti

Trie duomenų struktūra | Įterpti ir ieškoti

The Išbandykite duomenų struktūrą yra į medį panaši duomenų struktūra, naudojama dinaminiam eilučių rinkiniui saugoti. Jis dažniausiai naudojamas siekiant efektyvumo atgavimas ir saugykla raktų dideliame duomenų rinkinyje. Struktūra palaiko tokias operacijas kaip įterpimas , Paieška , ir ištrynimas raktų, todėl tai yra vertinga priemonė tokiose srityse kaip kompiuterių mokslas ir informacijos paieška. Šiame straipsnyje mes ketiname ištirti įterpimas ir paieška operaciją „Trie Data Structure“.

Išbandykite duomenų struktūrą

Išbandykite duomenų struktūrą

Turinys

Žemiau pateikiamas pirmiau minėto metodo įgyvendinimas:

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) { // Jei dabartinio simbolio mazgas neegzistuoja // tada sukurkite naują mazgą TrieNode* newNode = new TrieNode();  // Išsaugokite naujai sukurto // mazgo nuorodą.  currentNode->childNode[c - 'a'] = naujasMazgas;  } // Dabar perkelkite esamo mazgo žymeklį į naujai // sukurtą mazgą.  currentMazgas = dabartinisMazgas->vaikasMazgas[c - 'a'];  } // Padidinkite paskutinio currentNode // rodyklės žodį EndCount. Tai reiškia, kad yra eilutė, kuri baigiasi // currentNode.  currentNode->wordEnd = 1; } bool search_key(TrieNode* root, string& key) { // Inicijuoti currentNode rodyklę // su šakniniu mazgu TrieNode* currentNode = root;  // Pakartokite per visą eilutę, skirtą (automatinis c : klavišas) { // Patikrinkite, ar yra dabartinio // simbolio mazgas trie.  if (currentNode->childNode[c - 'a'] == NULL) { // Duotas žodis neegzistuoja Trie return false;  } // Perkelkite currentNode žymeklį į jau // esamą dabartinio simbolio mazgą.  currentMazgas = dabartinisMazgas->vaikasMazgas[c - 'a'];  } return (currentNode->wordEnd == true); } // Tvarkyklės kodas int main() { // Sukurkite Trie TrieNode šakninį mazgą* root = new TrieNode();  // Saugo eilutes, kurias norime įterpti į // Trie vektorių inputStrings = { 'ir', 'ant', 'do', 'geek', 'dad', 'ball' };  // Trie įterpimo operacijų skaičius int n = inputStrings.size();  už (int i = 0; i < n; i++) {  insert_key(root, inputStrings[i]);  }  // Stores the strings that we want to search in the Trie  vector searchQueryStrings = { 'do', 'geek', 'bat' };  // paieškos operacijų skaičius Bandyk int searchQueries = searchQueryStrings.size();  už (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) =>try.insert(str)); const searchQueryStrings = ['do', 'geek', 'bat']; // Ieškokite kiekvienos eilutės ir atspausdinkite, ar ji rasta lauke Trie searchQueryStrings.forEach((query) => { console.log(`Užklausos eilutė: ${query}`); if (trie.search(query)) { console.log('Užklausos eilutė yra Trie' } else { console.log('Užklausos eilutės nėra Trie' });>>   
Išvestis Susiję straipsniai:

  • Pabandykite ištrinti
  • Rodomas Trie turinys
  • Automatinio užbaigimo funkcija naudojant „Trie“.
  • Šablonų paieška naudojant visų priesagų rinkinį
  • Praktikos problemos:

    • Minimali žodžių pertrauka
    • Unikalios eilutės dvejetainėje matricoje
    • Skirtingų poeilučių skaičius
    • Žodis nesuprantamas
    • Eilučių (arba žodžių) masyvo rūšiavimas naudojant Trie