Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. public class WordDictionary {
  2.    
  3.     private readonly Dictionary<int, HashSet<string>> _data = new Dictionary<int, HashSet<string>>();
  4.     private readonly Dictionary<string, bool> _searchResults = new Dictionary<string, bool>();
  5.  
  6.     /** Initialize your data structure here. */
  7.     public WordDictionary() {
  8.        
  9.     }
  10.    
  11.     /** Adds a word into the data structure. */
  12.     public void AddWord(string word) {
  13.         if(string.IsNullOrEmpty(word))
  14.             return;
  15.        
  16.         if(!_data.ContainsKey(word.Length))
  17.             _data[word.Length] = new HashSet<string>();
  18.        
  19.         if(_data[word.Length].Add(word))
  20.         {    
  21.             foreach(var kvp in _searchResults.ToArray())
  22.             {
  23.                 if(!kvp.Value && kvp.Key.Length == word.Length)
  24.                     _searchResults.Remove(kvp.Key);
  25.             }
  26.         }
  27.     }
  28.    
  29.     /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
  30.     public bool Search(string searchWord) {
  31.        
  32.         if(string.IsNullOrEmpty(searchWord))
  33.             return false;
  34.        
  35.         if(searchWord.Contains("."))
  36.         {        
  37.             if(_searchResults.ContainsKey(searchWord))
  38.                 return _searchResults[searchWord];
  39.            
  40.             if(!_data.ContainsKey(searchWord.Length))
  41.                 return false;
  42.            
  43.             var regex = new System.Text.RegularExpressions.Regex($"^{searchWord}$");
  44.             foreach(var word in _data[searchWord.Length])
  45.             {
  46.                 if(regex.IsMatch(word))
  47.                     return _searchResults[searchWord] = true;
  48.             }
  49.            
  50.             return _searchResults[searchWord] = false;
  51.         }
  52.        
  53.         return _data.ContainsKey(searchWord.Length)
  54.             && _data[searchWord.Length].Contains(searchWord);
  55.     }
  56. }
  57.  
  58. /**
  59.  * Your WordDictionary object will be instantiated and called as such:
  60.  * WordDictionary obj = new WordDictionary();
  61.  * obj.AddWord(word);
  62.  * bool param_2 = obj.Search(word);
  63.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement