Skip to content

Commit

Permalink
Implement Trie (Prefix Tree)
Browse files Browse the repository at this point in the history
  • Loading branch information
eunhwa99 committed Jan 5, 2025
1 parent 0bc0ac8 commit 6341418
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions implement-trie-prefix-tree/eunhwa99.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.HashMap;
import java.util.Map;

// insert ์‹œ, ๋ฌธ์ž์—ด์˜ prefix๋ฅผ ๋‹ค Map์— ์ €์žฅํ•˜๊ณ , ํ•ด๋‹น ๋ฌธ์ž์—ด์€ prefix ์ด๋ฏ€๋กœ boolean false ๋กœ ์„ค์ •
// prefix๊ฐ€ ์•„๋‹Œ ์˜จ์ „ํ•œ ๋ฌธ์ž์—ด ์‚ฝ์ž…์€ true ๋กœ ์ €์žฅ

// search ์‹œ, Map์— ํ•ด๋‹น ๋‹จ์–ด๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ , boolean ๊ฐ’์ด true ์ธ์ง€ ํ™•์ธ
// startsWith๋Š” ๊ทธ๋ƒฅ Map ์— ํ•ด๋‹น ๋ฌธ์ž์—ด์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋ฉด ๋œ๋‹ค.

// ๊ณต๊ฐ„ ๋ณต์žก๋„: Map ํฌ๊ธฐ -> O(N)
// ์‹œ๊ฐ„ ๋ณต์žก๋„: ์ „์ฒด ํ˜ธ์ถœ ์ˆ˜ * String ๊ธธ์ด -> O(N*M)
// ์ฐธ๊ณ ) ์ตœ๋Œ€ ์‹œ๊ฐ„ ๋ณต์žก๋„ : 2000 * 3*10^4 = 6*10^7
class Trie {

Map<String,Boolean> stringSet;
public Trie() {
stringSet = new HashMap<>();
}

public void insert(String word) {
for(int i=0;i<word.length();i++){
stringSet.putIfAbsent(word.substring(0, i), false);
}
stringSet.put(word, true);
}

public boolean search(String word) {
return stringSet.containsKey(word) && stringSet.get(word)==true;
}

public boolean startsWith(String prefix) {

return stringSet.containsKey(prefix);
}
}

0 comments on commit 6341418

Please sign in to comment.