[Java] 백준(브론즈-2) 2920번 - 음계

문제 풀이
이 문제는 ascending 계열과 descending 계열 두가지 패턴으로 주어졌을 때만 고려하면 된다.
아이디어 도출
- ascending 계열 [1,2,3,4,5,6,7,8]과 descending 계열 [8,7,6,5,4,3,2,1] 두 가지 방식을 공백없는 문자열로 생성한다.
- 주어진 문자열과 ascending 문자열을, descending 문자열을 비교한다.
- 두 문자열과 다르다면 mixed를 출력하고 ascending 문자열과 같다면 ascending을, descending 문자열과 같다면 descending을 출력한다.
1
2
3
String ascending = "12345678";
String descending = "87654321";
String str = br.readLine().replace(" ", "");
ascending과 descending 문자열을 생성하고 주어진 문자열을 공백없이 String형으로 만들자.
1
2
3
if(str.equals(ascending)) bw.write("ascending"+"\n");
else if(str.equals(descending)) bw.write("descending"+"\n");
else bw.write("mixed"+"\n");
주어진 문자열이 ascending 문자열과 같다면 ascending을, descending 문자열과 같다면 descending을 출력하고
두 문자열에 포함되지 않는다면 mixed를 출력한다.
작성코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String ascending = "12345678";
String descending = "87654321";
String str = br.readLine().replace(" ", "");
if(str.equals(ascending)) bw.write("ascending"+"\n");
else if(str.equals(descending)) bw.write("descending"+"\n");
else bw.write("mixed"+"\n");
bw.flush();
bw.close();
br.close();
}
}
회고
- 문제에서 요구하는 ascending descending 두가지를 충족하면 되기에 미리 두가지 경우의 수를 모두 비교하여 검증할 수 있었다.
- 단순하게 두가지 경우의 수의 범위를 요구했기에 가능한 풀이였다고 생각한다.
출처
- 해당 문제의 저작권은 문제를 만든이에게 있으며 자세한 내용은 문제 링크에서 참조바랍니다.