🎊 정답 코드
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int count = 0;
int i = 0;
while (i < input.length()) {
// dz= 패턴 먼저 찾기
if (i+2 < input.length() && input.substring(i, i+3).equals("dz=")){
count++;
i += 3;
}
// 마지막 한글자 이전까지 두글자 체크
else if (i+1 < input.length()) {
String two = input.substring(i, i+2);
if (two.equals("c=") || two.equals("c-") ||
two.equals("d-") || two.equals("lj") ||
two.equals("nj") || two.equals("s=") ||
two.equals("z=")) {
count++;
i += 2;
}
else {
count++;
i++;
}
}
// 마지막 한 글자
else {
count++;
i++;
}
}
System.out.println(count);
}
}
🔍 조건문 흐름 설명
조건 분기 설명 조건
조건 분기 | 설명 | 조건 |
if | dz=가 있는 경우 (3글자) | i+2 < length && substring(i, i+3) == "dz=" |
else if 내부 if | 나머지 크로아티아 알파벳 (2글자) | "c=", "c-", "d-", "lj", "nj", "s=", "z=" |
else if 내부 else | 그냥 한 글자 처리 | - |
else | 마지막 남은 한 글자 | - |
🧪 예시 문자열: "ljes=njak"
단계 현재 인덱스 (i) 현재 문자 / 패턴 어떤 조건에 해당? 증가한 i 누적 count
i | 현재 문자 | 어떤 조건인지 | 증가한 i | count |
0 | lj | else if 내부 if | +2 → 2 | 1 |
2 | e | else if 내부 else (매칭 없음) | +1 → 3 | 2 |
3 | s= | else if 내부 if | +2 → 5 | 3 |
5 | nj | else if 내부 if | +2 → 7 | 4 |
7 | a | else if 내부 else | +1 → 8 | 5 |
8 | k | else (마지막 글자) | +1 → 9 | 6 |
🔧 substring() 메서드
- substring(i, j)는 i번 인덱스부터 j-1번 인덱스까지 잘라낸 문자열을 반환합니다.
- 즉, 문자열 "ljes=njak"에서 input.substring(0, 2)은 "lj"를 반환합니다.
- 자바에서 substring(a, b)는 a <= index < b 범위의 문자열을 의미하므로, 끝 인덱스는 포함되지 않습니다.
'코딩 테스트 일지 📒' 카테고리의 다른 글
[백준] 16953 A → B | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.27 |
---|---|
[백준] 10026 적록색약 | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.26 |
[백준] 11725 트리의 부모 찾기 | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.25 |
[백준] 11724 연결 요소의 개수 | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.24 |
[백준] 2667 단지번호붙이기 | DFS, BFS, 그래프 | 실버 Ⅰ | JAVA (1) | 2024.11.22 |