Home BOJ. String set (14425)
Post
Cancel

BOJ. String set (14425)

[Link] https://www.acmicpc.net/problem/14425


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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int[] arr = getArr();
		int n = arr[0], m = arr[1];
		Trie trie = new Trie();
		int cnt = 0;

		for(int i = 0; i < n; i++) trie.add(br.readLine());
		for(int i = 0; i < m; i++) if(trie.contains(br.readLine())) cnt++;

		print(cnt);
	}

	static class Trie {
		Trie[] arr = new Trie[26];
		boolean end = false;

		public void add(String s) {
			Trie trie = this;
			for(int i = 0; i < s.length(); i++) {
				char ch = s.charAt(i);
				if(trie.arr[ch - 'a'] == null) trie.arr[ch - 'a'] = new Trie();
				trie = trie.arr[ch - 'a'];
			}
			trie.end = true;
		}

		public boolean contains(String s) {
			Trie trie = this;
			for(int i = 0; i < s.length(); i++) {
				char ch = s.charAt(i);
				if(trie.arr[ch - 'a'] == null) return false;
				trie = trie.arr[ch - 'a'];
			}
			return trie.end;
		}
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.