-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1032-StreamOfCharacters.cs
66 lines (54 loc) · 1.82 KB
/
1032-StreamOfCharacters.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//-----------------------------------------------------------------------------
// Runtime: 628ms
// Memory Usage: 73.8 MB
// Link: https://leetcode.com/submissions/detail/385354300/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _1032_StreamOfCharacters
{
private readonly Trie root;
private readonly List<char> stream;
public _1032_StreamOfCharacters(string[] words)
{
root = new Trie();
stream = new List<char>();
foreach (var word in words)
{
var current = root;
foreach (var ch in new string(word.Reverse().ToArray()))
{
if (current.Children[ch - 'a'] == null)
current.Children[ch - 'a'] = new Trie();
current = current.Children[ch - 'a'];
}
current.IsFinished = true;
}
}
public bool Query(char letter)
{
stream.Add(letter);
var current = root;
for (int i = stream.Count - 1; i >= 0; i--)
{
if (current.IsFinished) return true;
if (current.Children[stream[i] - 'a'] == null)
return false;
current = current.Children[stream[i] - 'a'];
}
return current.IsFinished;
}
public class Trie
{
public Trie[] Children { get; } = new Trie[26];
public bool IsFinished { get; set; }
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* bool param_1 = obj.Query(letter);
*/
}