์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Java

[BOJ/Step7] 10809 : ์•ŒํŒŒ๋ฒณ ์ฐพ๊ธฐ (JAVA)

NaNaRin๐Ÿ™ƒ 2021. 1. 11. 13:49

www.acmicpc.net/problem/10809

 

10809๋ฒˆ: ์•ŒํŒŒ๋ฒณ ์ฐพ๊ธฐ

๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์— ๋Œ€ํ•ด์„œ, a๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, b๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, ... z๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ, ์–ด๋–ค ์•ŒํŒŒ๋ฒณ์ด ๋‹จ์–ด์— ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š๋‹ค๋ฉด -1์„ ์ถœ

www.acmicpc.net


๋ฌธ์ œ

์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์— ๋Œ€ํ•ด์„œ, ๋‹จ์–ด์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ, ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” -1์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ๋‹จ์–ด S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 100์„ ๋„˜์ง€ ์•Š์œผ๋ฉฐ, ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

 

์ถœ๋ ฅ

๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์— ๋Œ€ํ•ด์„œ, a๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, b๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜, ... z๊ฐ€ ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•œ๋‹ค.

๋งŒ์•ฝ, ์–ด๋–ค ์•ŒํŒŒ๋ฒณ์ด ๋‹จ์–ด์— ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š๋‹ค๋ฉด -1์„ ์ถœ๋ ฅํ•œ๋‹ค. ๋‹จ์–ด์˜ ์ฒซ ๋ฒˆ์งธ ๊ธ€์ž๋Š” 0๋ฒˆ์งธ ์œ„์น˜์ด๊ณ , ๋‘ ๋ฒˆ์งธ ๊ธ€์ž๋Š” 1๋ฒˆ์งธ ์œ„์น˜์ด๋‹ค.

 

์˜ˆ์ œ ์ž…๋ ฅ

baekjoon

 

์˜ˆ์ œ ์ถœ๋ ฅ

1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1


ํ’€์ด

1. ๋‹จ์–ด s๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.

2. ์•ŒํŒŒ๋ฒณ ๋ฐฐ์—ดarray[26]์„ ์ƒ์„ฑ, -1๋กœ ์ดˆ๊ธฐํ™”

3. ์ž…๋ ฅ๋ฐ›์€ ๋‹จ์–ด s๋ฅผ ์ฒซ๊ธ€์ž๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ๋ถˆ๋Ÿฌ์™€์„œ ํ•ด๋‹น ๋ฐฐ์—ด์— index i ๊ฐ’์„ ์ €์žฅ

   => charAt() ๋ฉ”์†Œ๋“œ ์‚ฌ์šฉ

   => charํ˜• ๋ฌธ์ž๋ฅผ int๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ์•„์Šคํ‚ค์ฝ”๋“œ ๊ฐ’์ด ๋˜๋ฏ€๋กœ 97์„ ๋นผ๋ฉด ๋ฐฐ์—ด index๊ฐ’์œผ๋กœ ๋งž์ถœ ์ˆ˜ ์žˆ๋‹ค.

       (a์˜ ์•„์Šคํ‚ค์ฝ”๋“œ ๊ฐ’์ด 97)

4. ์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š” ์œ„์น˜๋ฅผ ์ถœ๋ ฅํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— array[num]์ด 0์ด์ƒ์ด๋ฉด continue

5. array[]๋ฅผ ์ถœ๋ ฅ

 

import java.util.Scanner;

public class B10809 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		String s = sc.nextLine();
		
		int[] array = new int [26];
		
		for(int i = 0; i < array.length; i++) {
			array[i] = -1;
		}

		for(int i = 0; i < s.length(); i++) {
			int num = s.charAt(i)-97;
			if(array[num] >= 0) {
				continue;
			}
			array[num] = i; 
		}
		
		for(int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}
	}

}