Skip to content

Commit 4517980

Browse files
authored
DFS 사용
1 parent 4158189 commit 4517980

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
public class LetterNode
2+
{
3+
public LetterNode[] Alphabet { get; } = new LetterNode[26]; // Initialize to null
4+
public bool IsEnd { get; set; }
5+
}
6+
7+
public class WordDictionary
8+
{
9+
private LetterNode root;
10+
11+
public WordDictionary()
12+
{
13+
root = new LetterNode();
14+
}
15+
16+
public void AddWord(string word)
17+
{
18+
LetterNode currentNode = root;
19+
foreach (char c in word)
20+
{
21+
int index = c - 'a';
22+
if (currentNode.Alphabet[index] == null)
23+
{
24+
currentNode.Alphabet[index] = new LetterNode();
25+
}
26+
currentNode = currentNode.Alphabet[index];
27+
}
28+
currentNode.IsEnd = true;
29+
}
30+
31+
public bool Search(string word)
32+
{
33+
return Dfs(word, root);
34+
}
35+
36+
private bool Dfs(string target, LetterNode currentRoot)
37+
{
38+
if (target.Length == 0)
39+
{
40+
return currentRoot.IsEnd;
41+
}
42+
43+
char firstLetter = target[0];
44+
string remainingTarget = target.Substring(1);
45+
46+
if (firstLetter == '.')
47+
{
48+
for (int i = 0; i < 26; i++)
49+
{
50+
if (currentRoot.Alphabet[i] != null && Dfs(remainingTarget, currentRoot.Alphabet[i]))
51+
{
52+
return true;
53+
}
54+
}
55+
}
56+
else
57+
{
58+
int index = firstLetter - 'a';
59+
if (currentRoot.Alphabet[index] != null)
60+
{
61+
return Dfs(remainingTarget, currentRoot.Alphabet[index]);
62+
}
63+
}
64+
65+
return false;
66+
}
67+
}

0 commit comments

Comments
 (0)