Archive

BOJ. String set (14425)

Archived technical note: BOJ. String set (14425).

On this page

Problem: BOJ 14425 — String Set · 한국어 · 日本語

The problem gives N strings to store and M strings to check. Count how many check strings are present among the stored strings. Every string contains only lowercase English letters.

Hash set

Store the input strings in a HashSet<String>. Inserting the same string more than once leaves the set unchanged, so duplicate stored strings do not affect the result. For each query, use contains to test exact whole-string membership and increment the count if it is present. Each query is processed once, so it contributes at most one to the answer.

Hash-set insertion and membership checks take expected O(L) time for a string of length L, including hashing and comparing string contents. Across all inserted strings and queries, the expected total time is O(total characters). The set uses O(total characters) space for the distinct stored strings.

Java

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));
		int[] arr = getArr();
		int n = arr[0], m = arr[1];
		Set<String> words = new HashSet<>();

		for(int i = 0; i < n; i++) words.add(br.readLine());

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

		System.out.print(count);
	}

	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
}