✏️ 문제풀이/백준

[백준/Java] 10809번 :: 알파벳 찾기

bono-hye 2024. 4. 9. 19:26

 

1) Scanner 사용

import java.util.Scanner;

public class Main
{
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		
		String word = sc.next();
		int[] array = new int[26];		// 전체 알파벳 길이의 배열 생성
		
		for(int i=0; i<26; i++)
			array[i] = -1;				// 초기값 -1로 설정 (해당하는 알파벳이 없을 경우 -1이 출력되어야 하기 때문)
		
		for(int i=0; i<word.length(); i++)
		{
			char a = word.charAt(i);
		
			if(array[a - 'a'] == -1)	// 위에서 얻어 낸 아스키 코드에서 -97 (a)한 값이 -1이라면 (즉, 있는 알파벳일 경우)
				array[a - 'a'] = i;		// i값으로 재설정 해준다.
		}
		
		for (int i=0; i < 26; i++)
			System.out.print(array[i] + " ");
		
		
		sc.close();
	}
}

 

 

2) BufferedReader 사용

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));
		
		String word = br.readLine();
		int[] array = new int[26];		
		
		for(int i=0; i<26; i++)
			array[i] = -1;				
		
		for(int i=0; i<word.length(); i++)
		{
			char a = word.charAt(i);
		
			if(array[a - 'a'] == -1)	
				array[a - 'a'] = i;		
		}
		
		for (int i=0; i < 26; i++)
			System.out.print(array[i] + " ");
	}
}

 

💡 정리

처음에는 int 배열을 구성해놓고 [알파벳이 있으면 위치 출력, 없으면 -1 출력] 이렇게 코드를 작성하려 했다가

-1로 셋팅하고 시작하는게 더 간단할 것 같다는 생각이 들었다! 

위 방식대로 풀어서 문제 풀이 완료~!