새발블로그
[백준/Java] 14425 문자열 집합 본문
문제
https://www.acmicpc.net/problem/14425
풀이방법
부분문자열이 아닌 문자 자체랑 일치하는지 판단하므로, 기준이 되는 단어를 집합에 저장하고, 입력받은 문자열을 비교한다.
Java에서 Set, HashMap, add(), contains() 문법 정리
1. Set과 HashSet
- Set<T>은 중복을 허용하지 않는 자료구조이며, 대표적으로 HashSet<T>을 많이 사용함.
- HashSet<T>은 내부적으로 해시 테이블을 사용하여 검색 속도가 빠름 (O(1))
- 순서를 보장하지 않음.
사용법
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // 중복된 값은 추가되지 않음
System.out.println(set.contains("banana")); // true
System.out.println(set.contains("grape")); // false
1. Set<T> 관련 메서드
1.1 add(E e)
- 요소 추가 (중복된 값은 추가되지 않음)
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // 중복된 값은 추가되지 않음
System.out.println(set); // [apple, banana]
1.2 remove(Object o)
- 특정 요소 삭제 (존재하지 않으면 아무런 동작도 하지 않음)
set.remove("apple");
System.out.println(set); // [banana]
1.3 contains(Object o)
- 요소가 존재하는지 확인 (true / false 반환)
System.out.println(set.contains("banana")); // true
System.out.println(set.contains("grape")); // false
1.4 size()
- Set에 저장된 요소 개수 반환
System.out.println(set.size()); // 1
1.5 isEmpty()
- Set이 비어있는지 확인 (true / false 반환)
System.out.println(set.isEmpty()); // false
set.clear(); // 모든 요소 삭제
System.out.println(set.isEmpty()); // true
1.6 clear()
- Set의 모든 요소 제거
set.clear();
System.out.println(set.size()); // 0
1.7 iterator()
- Set의 요소를 하나씩 순회할 때 사용
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (int num : numbers) {
System.out.println(num);
}
// 또는 Iterator 사용
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
2. HashMap
- HashMap<K, V>은 Key-Value 형태로 데이터를 저장하는 자료구조.
- HashSet과 마찬가지로 해시 테이블을 사용하여 빠르게 검색 가능 (O(1))
- Key는 중복 불가, Value는 중복 가능.
사용법
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
map.put("grape", 2);
System.out.println(map.get("banana")); // 5
System.out.println(map.containsKey("grape")); // true
System.out.println(map.containsValue(10)); // false
2. HashMap<K, V> 관련 메서드
2.1 put(K key, V value)
- Key-Value 쌍 추가 (동일한 Key가 있으면 기존 Value를 덮어씀)
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
map.put("apple", 10); // 기존 apple의 값이 10으로 변경됨
2.2 get(Object key)
- 해당 Key에 대한 Value를 반환 (없으면 null 반환)
System.out.println(map.get("banana")); // 5
System.out.println(map.get("grape")); // null
2.3 remove(Object key)
- 특정 Key 삭제 (Key가 없으면 아무 일도 없음)
map.remove("apple");
System.out.println(map); // {banana=5}
2.4 containsKey(Object key)
- 특정 Key가 존재하는지 확인
System.out.println(map.containsKey("banana")); // true
System.out.println(map.containsKey("grape")); // false
2.5 containsValue(Object value)
- 특정 Value가 존재하는지 확인
System.out.println(map.containsValue(5)); // true
System.out.println(map.containsValue(10)); // false
2.6 size()
- Key-Value 쌍의 개수 반환
System.out.println(map.size()); // 1
2.7 isEmpty()
- HashMap이 비어있는지 확인
System.out.println(map.isEmpty()); // false
map.clear();
System.out.println(map.isEmpty()); // true
2.8 clear()
- 모든 Key-Value 삭제
map.clear();
System.out.println(map.size()); // 0
2.9 keySet()
- 모든 Key를 Set 형태로 반환
map.put("apple", 3);
map.put("banana", 5);
map.put("grape", 2);
System.out.println(map.keySet()); // [apple, banana, grape]
2.10 values()
- 모든 Value를 Collection 형태로 반환
System.out.println(map.values()); // [3, 5, 2]
2.11 entrySet()
- 모든 Key-Value 쌍을 Set<Map.Entry<K, V>> 형태로 반환 (Key와 Value 동시 접근 가능)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
nextInt()의 개행 문제
nextInt() 사용 시 nextLine()을 추가해야 하는 이유
- nextInt()는 숫자만 입력받고 개행 문자(\n)는 버퍼에 남아 있음.
- 이후 nextLine()을 사용하면 버퍼에 남아 있던 개행 문자가 입력으로 처리됨.
- 이를 방지하기 위해 nextLine()을 한 번 호출하여 개행 문자를 제거해야 함.
잘못된 예제
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.nextLine(); // 버퍼에 남아 있던 개행 문자가 그대로 들어감
System.out.println("입력값: " + s); // 빈 문자열 출력
올바른 예제
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine(); // 개행 문자 제거
String s = sc.nextLine(); // 정상적으로 문자열 입력 가능
System.out.println("입력값: " + s);
풀이
import java.io.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
Set<String> word = new HashSet<>();
int N = sc.nextInt();
int M = sc.nextInt();
sc.nextLine(); //nextInt는 개행문자를 제거하지 않아 nextLine을 추가해준다
for (int i = 0; i < N; i++) {
word.add(sc.nextLine());
}
int wordCnt = 0;
for (int i = 0 ;i<M; i++ ){
if (word.contains(sc.nextLine()) ) {
wordCnt ++;
}
}
System.out.println(wordCnt);
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
| [백준/Java] 11279 최대 힙 (0) | 2025.07.01 |
|---|---|
| [백준/Java] 18258 큐 2 (0) | 2025.04.02 |
| [백준/Java] 4949 균형잡힌 세상 (0) | 2025.03.30 |
| [백준/Java] 1541 잃어버린 괄호 (1) | 2025.03.26 |
| [백준/Java] 1157 단어 공부 (1) | 2025.03.24 |