🤷‍♂️Algorithm

[트리] 트라이

말동말동현 2024. 5. 15. 21:55

트라이는 문자열 검색을 빠르게 실행할 수 있도록 설계한 트리 형태의 자료구조이다.

 

트라이의 핵심이론

트라이는 일반적으로 단어들을 사전의 형태로 생성한 후 트리의 부모 자식 노드 관계를 이용해 검색을 수행한다.

N진 트리 : 문자 종류의 개수에 따라 N이 결정된다. 예를 들어 알파벳은 26개의 문자이므로 26진 트리로 구성된다.

루트 노드는 항상 빈 문자열을 뜻하는 공백 상태를 유지한다.

 

https://www.acmicpc.net/problem/14425

 

 

코드1

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;


public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            map.put(br.readLine(), 0);
        }
        int count = 0;

        for (int i = 0; i < m; i++) {
            if(map.containsKey(br.readLine())) count++;
        }

        System.out.println(count);
    }
}

 

 

코드2

import java.io.*;
import java.util.*;

class tNode {
    tNode[] next = new tNode[26];
    boolean isEnd;
}

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        tNode root = new tNode();
        while(n > 0) {
            String text = sc.next();
            tNode now = root;
            for (int i = 0; i < text.length(); i++) {
                char c = text.charAt(i);
                if (now.next[c - 'a'] == null) {
                    now.next[c - 'a'] = new tNode();
                }
                now = now.next[c - 'a'];
                if (i == text.length() - 1)
                    now.isEnd = true;
            }
            n--;
        }
        int count = 0;
        while (m > 0) {
            String text = sc.next();
            tNode now = root;
            for (int i = 0; i < text.length(); i++) {
                char c = text.charAt(i);
                if (now.next[c - 'a'] == null) {
                    break;
                }
                now = now.next[c - 'a'];
                if (i == text.length() - 1 && now.isEnd)
                    count++;
            }
            m--;
        }
        System.out.println(count);
    }

}

 

코드1 이 훨씬 이해하기도 쉽고 쉬워보인다.