Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준 JAVA] 10809번 - 알파벳 찾기 본문

오늘의 문제

[백준 JAVA] 10809번 - 알파벳 찾기

jeongwon_ 2022. 6. 2. 22:13

문제 :

 

 

10809번: 알파벳 찾기

각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다. 만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출

www.acmicpc.net


약식 순서도 : 

- 문자열을 입력받아 String(str)에 저장한다.

- index값 저장을 위한 int 배열(arr)을 소문자 알파벳 개수(26) 크기로 생성 후 모든 값을 -1로 초기화한다.

- 반복문 내에서 문자열의 각 index에 해당하는 문자를 'a'~'z'와 같은지 비교한다. (알파벳을 숫자로 치환해 1씩 더하는 방식으로)

- 동일한 값이 있으면 우선 arr[i]이 -1인지 확인 후 맞으면 해당 문자의 index값(i)를 배열 arr[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));
		String str = br.readLine();
		br.close();

		int[] arr = new int[26];
		for(int i=0; i<26; i++)
			arr[i]=-1;

		char c = 'a';

		for(int j=0; j<26; j++) {
			
			for(int i=0; i<str.length(); i++) {
				if(str.charAt(i)==c && arr[j]==-1) {//두 조건을 모두 만족하면
					arr[j]=i;	//배열에 값 저장
					break;	//outer for로 돌아감
				}								
			}
			c++;
		}
		
		for(int i : arr)
			System.out.print(i+" ");
	}
}

 

 

개선 답안 : (출처)https://st-lab.tistory.com/62

package practice;

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 str = br.readLine();
		br.close();

		int[] arr = new int[26];
		for(int i=0; i<26; i++)
			arr[i]=-1;
		
		for(int i = 0; i <str.length(); i++) {
			char ch = str.charAt(i);
    
			if(arr[ch - 'a'] == -1) {	// ch='b'라면 arr[1]이 된다.
				arr[ch - 'a'] = i;
			}
		}
		
		for(int i : arr)
			System.out.print(i+" ");
	}
}

시간과 메모리도 줄고, 반복문도 줄었다.