Advertisement
nullzero

Trie

Jul 21st, 2012
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4.  
  5. class Node{
  6.     const int ALL_CHAR = 26;
  7.     const int MAX_CHAR = 128;
  8.    
  9.     private static char []map_char_to_int = new char[MAX_CHAR];
  10.     private static char []map_int_to_char = new char[ALL_CHAR];
  11.     private Node[] Character = new Node[ALL_CHAR];
  12.     private int Count = 0;
  13.    
  14.     public void init(){
  15.         for(char i = 'a'; i <= 'z'; ++i){
  16.             map_char_to_int[i] = (char)(i - 'a');
  17.             map_int_to_char[i - 'a'] = i;
  18.         }
  19.     }
  20.    
  21.     private int _find(ref string str, int index){
  22.         if(index == str.Length) return ++this.Count;
  23.         if(Character[map_char_to_int[Convert.ToChar(str[index])]] == null)
  24.             Character[map_char_to_int[Convert.ToChar(str[index])]] = new Node();
  25.        
  26.         return Character[map_char_to_int[Convert.ToChar(str[index])]]._find(ref str, index + 1);
  27.     }
  28.    
  29.     public int Find(string str){
  30.         str = str.ToLower();
  31.         return _find(ref str, 0);
  32.     }
  33.    
  34.     private static StringBuilder current = new StringBuilder();
  35.  
  36.     public void DFS(){
  37.         if(Count > 0) Console.WriteLine("[{0}={1}] ", current, Count);
  38.         for(int i = 0; i < ALL_CHAR; i++){
  39.             if(Character[i] != null){
  40.                 current.Append(map_int_to_char[i]);
  41.                 Character[i].DFS();
  42.                 current.Remove(current.Length - 1, 1);
  43.             }
  44.         }
  45.     }
  46. }
  47.  
  48. class word{
  49.     public static void Main(){
  50.         Node trie = new Node();
  51.         trie.init();
  52.         try{
  53.             StreamReader inf = File.OpenText("sampletext.txt");
  54.             string line = inf.ReadLine();
  55.             while(line != null){
  56.                 string []sline = line.Split(' ');
  57.                 for(int i = 0; i < sline.Length; i++)
  58.                     trie.Find(sline[i]);
  59.                 line = inf.ReadLine();
  60.             }
  61.         }catch (Exception e){}
  62.         trie.DFS();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement