You are viewing a single comment's thread. Return to all comments →
C# solution using a tree where each node has potentially 26 children.
class Result { class Node { public int Count = 0; public Node[] Children = new Node[26]; } public static List<int> contacts(List<List<string>> queries) { List<int> counts = new List<int>(); Node root = new Node(); foreach (List<string> q in queries) { if (q[0] == "add") { Node currentNode = root; foreach (char c in q[1]) { if (currentNode.Children[c - 'a'] == null) { Node n = new Node(); n.Count = 1; currentNode.Children[c - 'a'] = n; } else { currentNode.Children[c - 'a'].Count++; } currentNode = currentNode.Children[c - 'a']; } } else if (q[0] == "find") { Node currentNode = root; int count = 0; int depth = 1; foreach (char c in q[1]) { if (currentNode.Children[c - 'a'] == null) break; if (q[1].Length == depth) count = currentNode.Children[c - 'a'].Count; depth++; currentNode = currentNode.Children[c - 'a']; } counts.Add(count); } }
return counts; }
}
Seems like cookies are disabled on this browser, please enable them to open this website
Contacts
You are viewing a single comment's thread. Return to all comments →
C# solution using a tree where each node has potentially 26 children.
}