

도대체 어떻게 풀지? 라는 생각으로 몇십분 가량 고민하다가...
에잇 모르겠다. 그냥 해보기로 하고 a to z를 전부 배열로 만들어버림..
처음에 작성한 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arrI = new int[26];
for (int i = 0; i < arrI.length; i++) {
arrI[i] = -1;
}
char[] arrS = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
String s = br.readLine();
for (int i = 0; i < s.length(); i++) {
char b = s.charAt(i);
for (int j = 0; j < arrS.length; j++) {
char c = arrS[j];
if(b == c) {
if(arrI[j] == -1) {
arrI[j] = i;
continue;
}
}
}
}
for (int i = 0; i < arrI.length; i++) {
System.out.print(arrI[i] + " ");
}
}
}

결과는 어찌저찌.. 저렇게 해도 맞다고 해주긴 하는데 영~ 찜찜하다.
내가 작성한 코드는 너무 하드코딩 되었다는 걸 나도 느꼈다.
그래서 남의 코드를 찾아봄
참고 코드 바탕으로 수정
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arrI = new int[26];
for (int i = 0; i < arrI.length; i++) {
arrI[i] = -1;
}
String s = br.readLine();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(arrI[ch - 'a'] == -1) {
arrI[ch - 'a'] = i;
}
}
for (int i = 0; i < arrI.length; i++) {
System.out.print(arrI[i] + " ");
}
}
}
이렇게 하니 훨~씬 간결해졌다.
알파벳 위치 가져오는 방법을 까먹었다.
String c = br.readLine();
System.out.println(c.charAt(0)-'a');
a 입력 시 0, z 입력 시 25
아스키 값 'a'를 빼주면 알파벳의 위치가 나온다.
오랜만에 풀었더니 폼 다 잃었네...
반응형
'코딩테스트 > 백준' 카테고리의 다른 글
| [백준 7489] 팩토리얼 JAVA (0) | 2024.11.07 |
|---|---|
| [백준 11718] 그대로 출력하기 JAVA (0) | 2024.10.30 |
| [백준 2588] 곱셈, [2908] 상수 JAVA (0) | 2024.01.29 |
| [백준 13241] 최소공배수 JAVA (0) | 2024.01.25 |
| [백준 3052] 나머지 JAVA (0) | 2024.01.23 |