๐ฉ๐ป ํธ๋ผ์ด (Trie)
๋ฌธ์์ด์ ์ ์ฅํ๊ณ ๋น ๋ฅด๊ฒ ํ์ํ๊ธฐ ์ํ ์ ๋ ฌ๋ ํธ๋ฆฌ ํํ์ ์๋ฃ๊ตฌ์กฐ
๋ฌธ์์ด ์ ์ฅ์ ์ํ ๋ฉ๋ชจ๋ฆฌ๊ฐ ํ์ํ์ง๋ง, ํ์์ด ๋น ๋ฆ ***
โ๏ธ ์๊ฐ ๋ณต์ก๋ ๋ฐ ์์ฑ ๋ณต์ก๋
๊ธธ์ด๊ฐ N์ธ ๋ฌธ์์ด ํ์์ ์๊ฐ ๋ณต์ก๋ :O(N)
์์ฑ ๋ณต์ก๋ : O(MN) (M: ๋ฌธ์์ด ๊ฐ์)
โ๏ธ ํธ๋ผ์ด ํํ
๋ฌธ์์ด ๊ตฌ์ฑ ex) apple, april, ace, bear, best
โ๏ธ ํธ๋ผ์ด์ ์ฝ์
์์ ์๋ ๊ฒ๊ณผ ๋น๊ตํ์ฌ ์๋ ๋ถ๋ถ์ ๊ทธ๋๋ก ๋ฐ๋ผ๊ฐ์ ์๋ ๋ถ๋ถ๋ถํฐ ๋ ธ๋๋ฅผ ์์ฑ, ๋ฌธ์์ ๋ ๋ ธ๋๋ ๋ฐ๋ก ํ๊ธฐ๋ฅผ ํด๋๋ค.
โ๏ธ ํธ๋ผ์ด์ ์ญ์
๋ฌธ์๋ฅผ ๋ฐ๋ผ๊ฐ์ ๋์ชฝ์ ๋ค๋ค๋ฅด๋ฉด, (<ex> apple์์์ e, app์์์ p )
- ํด๋น ์น ํด์ ธ์๋ ๋
ธ๋์ (๋ฌธ์์ด ๋ ๋
ธ๋์) ์์๋
ธ๋๊ฐ ์์ผ๋ฉด ์์น ํ ๊ฒ์ ์์ค ํ ์๋ก ์ด๋,
๊ทธ ๋ค์ ๋ ธ๋๊ฐ ์์๋ ธ๋๊ฐ ์๊ณ , ํฐ์ ๋ ธ๋ (๋ ๋ ธ๋๊ฐ ์๋๋ผ๋ฉด) ์ง์ด ํ ์๋ก ์ฌ๋ผ๊ฐ ์์๋ ธ๋๊ฐ ์๊ฑฐ๋ ๋ ๋ ธ๋ ์ผ๋๊น์ง ๋ฐ๋ณตํ๋ค. - ๋ง์ฝ ๋ฌธ์์ด์ ๋ ๋ ธ๋ ์๋ ์์๋ ธ๋๊ฐ ๋ ์กด์ฌํ๋ค๋ฉด ํด๋น ๋ ธ๋์ ์๋ง ํฐ์์ผ๋ก ๋ค์ ๋ฐ๊ฟ์ฃผ๋ฉด ๋๋ค.
โ๏ธ ํธ๋ผ์ด์ ๊ตฌํ
โจ Key, Value๋ก ์ด๋ฃจ์ด์ง ๋ ธ๋๋ก ๊ตฌ์ฑ
- Key : ์ํ๋ฒณ
- Value : ์์ ๋ ธ๋
Class Noe{
HashMap<Character, Node> child;
boolean isTerminal; // ํ์ฌ Node๊ฐ ๋จ์ด์ ๋ ๋
ธ๋์ธ์ง
}
โจ Java์์ Trie ๊ตฌํ
Class Node{
HashMap<Character, Node> child;
boolean isTerminal;
public Node(){
this.child = new HashMap<>();
this.isTerminal = false;
}
}
Class Trie{
Node root;
public Trie(){
this.root = new Node();
}
// ์ฝ์
public void insert(String str){
Node cur = this.root;
for(int i=0; i < str.length(); i++){
char c = str.charAt(i);
// *** HashMap<>()์ ์ ์ฅ๋ ๋ฉ์๋ putIfAbsent() ์ฌ์ฉ ***
// c ๊ฐ cur๊ธฐ์ค์ผ๋ก ์์๋
ธ๋๋ก ์์ผ๋ฉด ๋ฃ์ด์ฃผ๊ณ , ์๋ค๋ฉด ๋์ด๊ฐ๊ฒ ๋๋ค.
cur.child.putIfAbsent(c, new Node());
cur = cur.child.get(c);
if(i == str.length() - 1){
cur.isTerminal = true;
return;
}
}
}
// ํ์
public boolean search(String str){
Node cur = this.root;
for(int i=0; i<str.length(); i++){
char c = str.charAt(i);
if(cur.child.containsKey(c)){
cur = cur.child.get(c);
}else{
return false;
}
if(i == str.length() - 1){
if(!cur.isTerminal){
return flse;
}
}
}
return true;
}
// ์ญ์
public void delete(String str){
boolean ret = this.delete(this.root, str, 0);
if(ret){
System.out.println(str + " ์ญ์ ์๋ฃ");
}else{
System.out.println(str + " ๋จ์ด๊ฐ ์์ต๋๋ค.");
}
}
public boolean delete(Node node, String str, int idx){
char c = str.charAt(idx);
if(!node.child.containsKey(c)){
return false;
}
Node cur = node.child.get(c);
idx++;
if(idx == str.length()){
if(!cur.isTerminal){
return false;
}
// ๋จ์ด์ ๋ ๋
ธ๋๊ฐ ๋ง๋ค๋ฉด
cur.isTerminal = false;
if(cur.child.isEmpty()){ // ์๋ ๋ธ๋ฆฐ ์์๋
ธ๋๋ค์ด ์๋ค๋ฉด,
node.child.remove(c);
}
}
else{
if(!this.delete(cur, str, idx)){ // ์ฌ๊ทํจ์ ์งํ
return false;
}
if(!cur.isTerminal && cur.child.isEmpty()){ // ๋ ๋ฌธ์๋ ์๋๊ณ , ํด๋น ๋
ธ๋์์ ํ์๋๋ ๋ฌธ์๋ ์๋ค๋ฉด ๊ฐ์ด ์ญ์
node.child.remove(c);
}
}
return true;
}
}
'์๊ณ ๋ฆฌ์ฆ > ์๋ฃ๊ตฌ์กฐ ์ด๋ก ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ฐ์ ์์ ํ (Priority Queue) - ๋น์ ํ ์๋ฃ๊ตฌ์กฐ (0) | 2024.07.17 |
---|---|
๊ทธ๋ํ - ๋น์ ํ ์๋ฃ๊ตฌ์กฐ (0) | 2024.07.16 |
๊ท ํ ์ด์ง ํธ๋ฆฌ (by ์ด์ง ํ์ ํธ๋ฆฌ) (0) | 2024.07.12 |
์ด์ง ํ์ ํธ๋ฆฌ (Binary search tree) BST - ์๋ฃ๊ตฌ์กฐ (0) | 2024.07.03 |
java - ๋นํธ ์ฐ์ฐ์ (0) | 2024.06.26 |