Пример #1
0
        public int Sum(string prefix)
        {
            //GetPrefix Node
            MapSumTrieNode prefixNode = MapSumTrie.GetPrefixNode(prefix);

            //Get sum of all leaves.
            return(MapSumHelper(prefixNode));
        }
Пример #2
0
        public MapSumTrieNode GetPrefixNode(string prefix)
        {
            MapSumTrieNode current = root;

            for (int i = 0; i < prefix.Length; i++)
            {
                if (current.trieNodes[prefix[i] - 'a'] == null)
                {
                    return(null);
                }

                current = current.Next(prefix[i]);
            }
            return(current);
        }
Пример #3
0
        private int MapSumHelper(MapSumTrieNode node)
        {
            if (node == null)
            {
                return(0);
            }

            int sum = node.sum;

            foreach (MapSumTrieNode childNode in node.trieNodes)
            {
                sum += MapSumHelper(childNode);
            }

            return(sum);
        }
Пример #4
0
        public void Insert(string key, int val)
        {
            MapSumTrieNode current = root;

            for (int i = 0; i < key.Length; i++)
            {
                if (current.trieNodes[key[i] - 'a'] == null)
                {
                    current.trieNodes[key[i] - 'a'] = new MapSumTrieNode();
                }

                current = current.Next(key[i]);
            }
            current.word = key;
            current.sum  = val;
        }
Пример #5
0
 public MapSumTrie()
 {
     root = new MapSumTrieNode();
 }