Post

[BaekJoon] 14425번 - 문자열 집합 [Java][C++]

[BaekJoon] 14425번 - 문자열 집합 [Java][C++]

문제 링크


1. 문제 풀이


집합 $S$ 에 대해 집합 $S$ 에 포함됐는지 여부를 구하는 문제로 집합에 포함됐는지 확인할 수 있는 함수나 메서드를 활용하면 간단하게 해결할 수 있다.


2. 코드


1. 풀이 [Java]

conatins 메서드로 집합에 포함됐는지 여부를 간단하게 확인할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
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());

        Set<String> set = new HashSet<>();
        for (int i = 0; i < N; i++) {
            set.add(br.readLine());
        }

        int cnt = 0;
        for (int i = 0; i < M; i++) {
            if (set.contains(br.readLine())) cnt++;
        }

        System.out.println(cnt);
    }
}


2. 풀이 [C++]

count 함수로 집합에 포함됐는지 여부를 간단하게 확인할 수 있다.

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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m;
    cin >> n >> m;

    unordered_set<string> st;
    for (int i = 0; i < n; i++) {
        string s;
        cin >> s;
        st.insert(s);
    }

    int cnt = 0;
    for (int i = 0; i < m; i++) {
        string s;
        cin >> s;
        if (st.count(s)) cnt++;
    }

    cout << cnt;
}

This post is licensed under CC BY 4.0 by the author.