๊ธฐ๋ก๋ฐฉ

Lv.1 : ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ฐ™์€ ๊ธ€์ž ๋ณธ๋ฌธ

CodingTest/Java

Lv.1 : ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ฐ™์€ ๊ธ€์ž

Soom_1n 2023. 4. 18. 17:08

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • ๋ฌธ์ž์—ด S์˜ ๊ฐ ์ž๋ฆฌ ๋ฌธ์ž๋“ค์˜ ์™ผ์ชฝ์œผ๋กœ ์ž์‹ ๊ณผ ๊ฐ™์€ ๋ฌธ์ž ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ answer๋ฐฐ์—ด์— ๋‹ด์•„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
  • ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ž…๋ ฅ๋˜๋ฏ€๋กœ 26ํฌ๊ธฐ์˜ int๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด, ๊ฐ ๋ฌธ์ž์˜ ์ตœ์‹  ์œ„์น˜๋ฅผ ์ €์žฅํ•œ๋‹ค.
    • ์œ„์น˜๊ฐ€ ์ €์žฅ๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฉด -1์„ ์ €์žฅํ•œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.util.Arrays;

class Solution {
    public int[] solution(String s) {
        int[] answer = new int[s.length()];
        int[] alph = new int[26];
        Arrays.fill(alph, -1);
        
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (alph[c-'a'] > -1) {
                answer[i] = i - alph[c-'a'];
            }
            else {
                answer[i] = -1;
            }
            alph[c-'a'] = i;
        }
        
        return answer;
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • ์ธ๋ฑ์Šค 0๋ถ€ํ„ฐ ์นด์šดํŠธํ•˜๋ฏ€๋กœ, alph๋ฐฐ์—ด์„ -1๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  • ์ตœ๊ทผ ์ธ๋ฑ์Šค์™€ ํ˜„์žฌ ์ธ๋ฑ์Šค์˜ ๊ฑฐ๋ฆฌ๋ฅผ answer๋ฐฐ์—ด์— ์ €์žฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • alph๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค๋Š” ์•„์ด๋””์–ด๋ฅผ ์ƒ๊ฐํ•˜๋‹ˆ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

728x90