My C# soluction


  • 0
    R

    public class WordDictionary {
    private TrieNode root;
    public WordDictionary()
    {
    root = new TrieNode();

    }
    
    // Adds a word into the data structure.
    public void AddWord(String word) {
        var start = root;
        foreach (var ch in word)
        {
            if (!start.Neighbors.ContainsKey(ch))
            {
                var newnode = new TrieNode(ch);
                start.Neighbors.Add(ch, newnode);
            }
    
            start = start.Neighbors[ch];
        }
    
        start.IsEnd = true;
    }
    
    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    public bool Search(string word) {
         return SearchNode(word, 0, root);
    }
    
    public bool SearchNode(String word, int index, TrieNode parent)
    {
       if(index == word.Length)
        {
           if (parent.IsEnd)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        var start = parent;
        char ch = word[index];
        if (ch == '.')
        {
            foreach (KeyValuePair<char, TrieNode> keyPair in start.Neighbors)
            {
                if (SearchNode(word, index + 1, start.Neighbors[keyPair.Key]))
                {
                    return true;
    
                }
    
            }
            return false;
        }
        else
        {
            if (!start.Neighbors.ContainsKey((ch)))
            {
    
                return false;
            }
            else
            {
                start = start.Neighbors[ch];
                return  SearchNode(word, index+1, start);
            }
        }
      
    }
    

    }

    public class TrieNode
    {
    // Initialize your data structure here.
    public char Data;
    public bool IsEnd;
    public Dictionary<char, TrieNode> Neighbors;
    public TrieNode()
    {
    this.Data = '#';
    this.IsEnd = true;
    this.Neighbors = new Dictionary<char, TrieNode>();
    }

    public TrieNode(char ch)
    {
        this.Data = ch;
        this.IsEnd = false;
        this.Neighbors = new Dictionary<char, TrieNode>();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.