티스토리 뷰
도대체 어떻게 풀지? 라는 생각으로 몇십분 가량 고민하다가...
에잇 모르겠다. 그냥 해보기로 하고 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 (1) | 2024.01.29 |
[백준 13241] 최소공배수 JAVA (1) | 2024.01.25 |
[백준 3052] 나머지 JAVA (0) | 2024.01.23 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준알고리즘
- SpringBoot
- 알고리즘
- tomcat
- Apache
- 티스토리챌린지
- 트리
- BigDecimal
- 백준
- docker컨테이너
- 웹스퀘어
- google cloud run
- dockerspring
- docker배포
- 자바
- MySQL
- Spring
- docker
- 이클립스
- 노드
- 백준자바
- 클라우드
- db
- 톰캣
- 그리드
- websquare
- docker앱배포
- Java
- 오블완
- controller
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함