generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem34.cs
More file actions
74 lines (61 loc) · 1.97 KB
/
Problem34.cs
File metadata and controls
74 lines (61 loc) · 1.97 KB
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
67
68
69
70
71
72
73
74
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/implement-trie-prefix-tree/">Implement Trie (Prefix Tree)</see>.
/// </summary>
public class Problem34
{
private readonly TrieNode trie;
/// <summary>
/// Initializes a new instance of the <see cref="Problem34"/> class.
/// </summary>
public Problem34() => this.trie = new TrieNode();
/// <summary>
/// Inserts the string `word` into the trie.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="word">Word to insert.</param>
public void Insert(string word) => this.trie.Insert(word);
/// <summary>
/// Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="word">Word to search.</param>
/// <returns>True, if the word in the trie.</returns>
public bool Search(string word)
{
var node = this.trie;
foreach (var character in word)
{
var nextNode = node[character];
if (nextNode == null)
{
return false;
}
node = nextNode;
}
return !string.IsNullOrEmpty(node.Word);
}
/// <summary>
/// Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="prefix">Prefix to check.</param>
/// <returns>True, if there is the word with provided prefix.</returns>
public bool StartsWith(string prefix)
{
var node = this.trie;
foreach (var character in prefix)
{
var nextNode = node[character];
if (nextNode == null)
{
return false;
}
node = nextNode;
}
return true;
}
}