
내가 생각했을때 문제에서 원하는부분
The first line contains single integer n — the number of problem proposals received by the little brothers (1 ≤ n ≤ 100).
Next n lines contain titles of proposed problems, one per line. The length of each title does not exceed 30 characters.
Each title starts with an uppercase letter and contains only English letters, digits and underscores.
Output a single number — the maximal number of problems in a good contest. In case there is no good contest that may be arranged, output 0.
내가 이 문제를 보고 생각해본 부분
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
입력을 효율적으로 받기 위해 BufferedReader 객체를 만든다.
InputStreamReader(System.in)을 감싸서 표준 입력(키보드 입력) 스트림을 문자 단위로 읽을 수 있게 해준다.
이 구조는 자바에서 콘솔로부터 빠르고 편리하게 문자열을 입력받는 표준 방식이다.
int n = Integer.parseInt(br.readLine());
첫 줄에서 입력받는 문제의 개수 n을 문자열로 읽은 뒤 Integer.parseInt를 통해 정수로 변환한다.
이렇게 변환한 n은 다음 줄부터 몇 개의 문제 제목을 읽을지 결정하는 기준이 된다.
HashSet<Character> firstChars = new HashSet<>();
문제 제목들의 첫 글자들을 중복 없이 저장할 HashSet을 생성한다.
HashSet은 삽입, 탐색이 평균적으로 빠른(상수 시간) 특징이 있어 연속된 알파벳을 확인하는 데 유리하다.
for (int i = 0; i < n; i++) {
String title = br.readLine();
firstChars.add(title.charAt(0));
}
n번 반복하며 각 문제 제목을 문자열로 읽다.
각 제목의 첫 번째 글자(charAt(0))만 추출하여 firstChars 집합에 추가한다.
이렇게 하면 주어진 문제들 중 첫 글자가 어떤 알파벳들인지 중복 없이 저장할 수 있다.
int maxLength = 0;
for (char c = 'A'; c <= 'Z'; c++) {
if (firstChars.contains(c)) {
maxLength++;
} else {
break;
}
}
'A'부터 'Z'까지 알파벳 순서로 하나씩 검사한다.
현재 알파벳 c가 firstChars 집합에 존재하면 maxLength를 1 증가시켜 연속된 문제의 수를 센다.
만약 존재하지 않는 알파벳이 나오면 연속성이 깨진 것이므로 반복문을 멈춘다.
이 과정을 통해 'A'부터 연속적으로 문제 제목이 존재하는 최대 길이를 구한다.
System.out.println(maxLength);
br.close();
최종적으로 계산된 최대 연속 문제 개수(maxLength)를 출력한다.
마지막에 사용한 BufferedReader를 닫아 자원 누수를 방지한다.
코드로 구현
package baekjoon.baekjoon_32;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
// 백준 9443번 문제
public class Main1283 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
HashSet<Character> firstChars = new HashSet<>();
for (int i = 0; i < n; i++) {
String title = br.readLine();
firstChars.add(title.charAt(0));
}
int maxLength = 0;
// 'A'부터 시작해서 연속된 알파벳이 존재하는 최대 길이 찾기
for (char c = 'A'; c <= 'Z'; c++) {
if (firstChars.contains(c)) {
maxLength++;
} else {
break;
}
}
System.out.println(maxLength);
br.close();
}
}
코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.