-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
85 lines (76 loc) · 1.98 KB
/
Copy pathsolution.java
File metadata and controls
85 lines (76 loc) · 1.98 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
75
76
77
78
79
80
81
82
83
84
85
// 211. Design Add and Search Words Data Structure
// https://leetcode.com/problems/design-add-and-search-words-data-structure/
// Medium | Java | Accepted 2025-12-20
// Runtime 177 ms | Memory 274.1 MB
class WordDictionary {
class TrieNode{
private TrieNode[] arr;
private boolean isEnd;
public TrieNode()
{
arr = new TrieNode[26];
isEnd = false;
}
}
public TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode temp = root;
char[] charr = word.toCharArray();
for(char c : charr)
{
int i = c-'a';
if(temp.arr[i]==null)
{
temp.arr[i] = new TrieNode();
}
temp = temp.arr[i];
}
temp.isEnd = true;
}
public boolean search(String word) {
TrieNode temp = root;
char[] charr = word.toCharArray();
return recurse(temp, 0, charr);
}
public boolean recurse(TrieNode temp, int index, char[] charr)
{
if(index==charr.length)
{
return temp.isEnd;
}
if(charr[index]!='.')
{
if(temp.arr[charr[index]-'a']!=null)
{
return recurse(temp.arr[charr[index]-'a'], index+1, charr);
}
else
{
return false;
}
}
if(charr[index]=='.')
{
for(int i = 0; i<26; i++)
{
if(temp.arr[i]!=null)
{
if(recurse(temp.arr[i],index+1, charr))
{
return true;
}
}
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/