https://leetcode.com/problems/implement-trie-prefix-tree/description/
Implement Trie (Prefix Tree) - LeetCode
Can you solve this real interview question? Implement Trie (Prefix Tree) - A trie [https://en.wikipedia.org/wiki/Trie] (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There
leetcode.com
문자열을 저장하고 검색하는 Trie 클래스를 만드는 문제이다. 단순하게 List 클래스를 이용하여 해결해 주었다. insert 와 search의 경우 ArrayList 클래스의 기본 메서드를 이용해 주었으며
검색 시에는 리스트를 순회하며 substring 하여 prefix와 substring 한 결과를 비교해주었다.
public class Trie {
List<String> list;
public Trie() {
list = new ArrayList<>();
}
public void insert(String word) {
list.add(word);
}
public boolean search(String word) {
return list.contains(word);
}
public boolean startsWith(String prefix) {
for(int i = 0; i < list.size(); i++){
String str = list.get(i);
if(str.length() >= prefix.length()
&& str.substring(0, prefix.length()).equals(prefix)) return true;
}
return false;
}
}
/**
* 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);
*/
'Algolithm-Leetcode > Trie' 카테고리의 다른 글
| Replace Words (0) | 2026.08.26 |
|---|---|
| Longest Common Prefix (0) | 2026.08.22 |
| Word Search II (0) | 2026.08.16 |
| Design Add and Search Words Data Structure (0) | 2026.08.12 |