forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1804.java
75 lines (66 loc) · 2.35 KB
/
_1804.java
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
package com.fishercoder.solutions;
public class _1804 {
public static class Solution1 {
public static class Trie {
class TrieNode {
int count;
int wordsCount;
TrieNode[] children;
public TrieNode() {
this.children = new TrieNode[26];
}
boolean isWord;
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
if (node.children[c - 'a'].count < 0) {
node.children[c - 'a'].count = 0;
}
node.children[c - 'a'].count++;
node = node.children[c - 'a'];
}
node.isWord = true;
if (node.wordsCount < 0) {
node.wordsCount = 0;
}
node.wordsCount++;
}
public int countWordsEqualTo(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
return 0;
}
node = node.children[c - 'a'];
}
return node.isWord ? node.wordsCount : 0;
}
public int countWordsStartingWith(String prefix) {
TrieNode node = this.root;
for (char c : prefix.toCharArray()) {
if (node.children[c - 'a'] == null) {
return 0;
}
node = node.children[c - 'a'];
}
return node.count < 0 ? 0 : node.count;
}
public void erase(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
node.children[c - 'a'].count--;
node = node.children[c - 'a'];
}
node.wordsCount--;
}
}
}
}