File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .HashMap ;
2+ import java .util .Map ;
3+
4+ // insert ์, ๋ฌธ์์ด์ prefix๋ฅผ ๋ค Map์ ์ ์ฅํ๊ณ , ํด๋น ๋ฌธ์์ด์ prefix ์ด๋ฏ๋ก boolean false ๋ก ์ค์
5+ // prefix๊ฐ ์๋ ์จ์ ํ ๋ฌธ์์ด ์ฝ์
์ true ๋ก ์ ์ฅ
6+
7+ // search ์, Map์ ํด๋น ๋จ์ด๊ฐ ์๋์ง ํ์ธํ๊ณ , boolean ๊ฐ์ด true ์ธ์ง ํ์ธ
8+ // startsWith๋ ๊ทธ๋ฅ Map ์ ํด๋น ๋ฌธ์์ด์ด ์๋์ง ํ์ธํ๋ฉด ๋๋ค.
9+
10+ // ๊ณต๊ฐ ๋ณต์ก๋: Map ํฌ๊ธฐ -> O(N)
11+ // ์๊ฐ ๋ณต์ก๋: ์ ์ฒด ํธ์ถ ์ * String ๊ธธ์ด -> O(N*M)
12+ // ์ฐธ๊ณ ) ์ต๋ ์๊ฐ ๋ณต์ก๋ : 2000 * 3*10^4 = 6*10^7
13+ class Trie {
14+
15+ Map <String ,Boolean > stringSet ;
16+ public Trie () {
17+ stringSet = new HashMap <>();
18+ }
19+
20+ public void insert (String word ) {
21+ for (int i =0 ;i <word .length ();i ++){
22+ stringSet .putIfAbsent (word .substring (0 , i ), false );
23+ }
24+ stringSet .put (word , true );
25+ }
26+
27+ public boolean search (String word ) {
28+ return stringSet .containsKey (word ) && stringSet .get (word )==true ;
29+ }
30+
31+ public boolean startsWith (String prefix ) {
32+
33+ return stringSet .containsKey (prefix );
34+ }
35+ }
You canโt perform that action at this time.
0 commit comments