티스토리 뷰

기본 구현

class Trie {

	public static class Node {
		private boolean isEnd;
		private final Node[] next;

		public Node(int size) {
			this.isEnd = false;
			this.next = new Node[size];
		}

		public Node next(int v) {
			return this.next[v];
		}

		public boolean isEnd() {
			return isEnd;
		}
	}

	private final char start;
	private final int size;
	private final Node root;

	public Trie(char start, char end) {
		this.start = start;
		this.size = end - start + 1;
		this.root = new Node(size);
	}

	public void make(String s) {
		Node now = root;

		for (char c : s.toCharArray()) {
			if (now.next[c - start] == null) {
				now.next[c - start] = new Node(size);
			}
			now = now.next[c - start];
		}

		now.isEnd = true;
	}

	public Node getRoot() {
		return root;
	}
}

 

사용 예

백준 14425번 문제

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

class Trie {

	public static class Node {
		private boolean isEnd;
		private final Node[] next;

		public Node(int size) {
			this.isEnd = false;
			this.next = new Node[size];
		}

		public Node next(int v) {
			return this.next[v];
		}

		public boolean isEnd() {
			return isEnd;
		}
	}

	private final char start;
	private final int size;
	private final Node root;

	public Trie(char start, char end) {
		this.start = start;
		this.size = end - start + 1;
		this.root = new Node(size);
	}

	public void make(String s) {
		Node now = root;

		for (char c : s.toCharArray()) {
			if (now.next[c - start] == null) {
				now.next[c - start] = new Node(size);
			}
			now = now.next[c - start];
		}

		now.isEnd = true;
	}

	public Node getRoot() {
		return root;
	}
}

public class App {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st = new StringTokenizer(br.readLine());

		int N = Integer.parseInt(st.nextToken());
		int M = Integer.parseInt(st.nextToken());

		Trie t = new Trie('a', 'z');

		for (int i = 1; i <= N; i++) {
			t.make(br.readLine());
		}

		List<String> checks = new ArrayList<>(M);
		for (int i = 1; i <= M; i++) {
			checks.add(br.readLine());
		}

		Trie.Node root = t.getRoot();

		int result = 0;

		for (String check : checks) {
			Trie.Node now = t.getRoot();

			boolean ok = true;
			for (char c : check.toCharArray()) {
				if (now.next(c - 'a') == null) {
					ok = false;
					break;
				}

				now = now.next(c - 'a');
			}

			ok &= now.isEnd();
			result += (ok ? 1 : 0);
		}

		bw.write(String.valueOf(result));
		br.close();
		bw.close();
	}
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함