일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- attribute
- Python Implementation
- 운영체제
- 시바견
- DWG
- 715. Range Module
- Protocol
- Convert Sorted List to Binary Search Tree
- Regular Expression
- kaggle
- 프로그래머스
- 43. Multiply Strings
- 밴픽
- data science
- 315. Count of Smaller Numbers After Self
- t1
- 컴퓨터의 구조
- iterator
- Generator
- 109. Convert Sorted List to Binary Search Tree
- LeetCode
- shiba
- Decorator
- Python Code
- 파이썬
- Class
- Substring with Concatenation of All Words
- Python
- concurrency
- 30. Substring with Concatenation of All Words
Archives
- Today
- Total
Scribbling
[Java101] Trie Implementation 본문
LeetCode: 208. Implement Trie (Prefix Tree)
class TrieNode {
public boolean isWord = false;
public TrieNode[] children = new TrieNode[26];
}
class Trie {
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode cur = root;
for (int i=0; i<word.length(); i++) {
char c = word.charAt(i);
if (cur.children[c - 'a'] == null) cur.children[c - 'a'] = new TrieNode();
cur = cur.children[c - 'a'];
}
cur.isWord = true;
}
public boolean search(String word) {
TrieNode cur = root;
for (int i=0; i<word.length(); i++) {
char c = word.charAt(i);
if (cur.children[c - 'a'] == null) return false;
cur = cur.children[c - 'a'];
}
return cur.isWord;
}
public boolean startsWith(String prefix) {
TrieNode cur = root;
for (int i=0; i<prefix.length(); i++) {
char c = prefix.charAt(i);
if (cur.children[c - 'a'] == null) return false;
cur = cur.children[c - 'a'];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
'Computer Science > Java' 카테고리의 다른 글
[Java 101] 435. Non-overlapping Intervals - Comparator (0) | 2023.03.15 |
---|---|
[Java 101] 211. Design Add and Search Words Data Structure - trie (0) | 2023.03.11 |
[Java 101] 102. Binary Tree Level Order Traversal - Queue (0) | 2023.03.04 |
[Java101] LeetCode: 23. Merge k Sorted Lists: Priority Queue (0) | 2023.03.02 |
[Java 101] 20. Valid Parentheses: Stack (0) | 2023.02.23 |