Algorithm/[BOJ] - JAVA
[백준] 10809 : 알파벳 찾기 JAVA 풀이
Codew
2022. 5. 14. 17:43
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[] alphabet = new int[26]; // 알파벳 개수의 크기만큼 배열 생성
for(int i=0;i<alphabet.length;i++){
alphabet[i] = -1; // -1로 초기화
}
int idx = 0; // 입력된 문자열 중 알파벳이 등장하는 첫 위치를 체크하기 위한 변수
for(byte val : br.readLine().getBytes()){ // 입력받은 문자열을 한 바이트씩 읽어옴
if(alphabet[val-97]==-1){ // 처음 등장한 알파벳이라면
alphabet[val-97] = idx; // 처음 등장한 인덱스를 배열에 저장
}
idx++;
}
for(int a : alphabet){
System.out.printf("%d ", a); // 알파벳 배열을 출력함
}
}
}
다시 풀어봤는데 이 코드가 좀 더 간결한 것 같다.
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int[] alphabet = new int[26];
for(int i=0;i<alphabet.length;i++){
alphabet[i] = -1;
}
for(int i=0;i<str.length();i++){
if(alphabet[str.charAt(i)-'a']==-1){
alphabet[str.charAt(i)-'a'] = i;
}
}
for(int val : alphabet){
System.out.print(val+" ");
}
}
}