๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Java] [Level2] ์˜์–ด ๋๋ง์ž‡๊ธฐ

Dbswnstjd 2024. 1. 11. 16:11

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/12981?language=java

 

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

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

programmers.co.kr

ํ’€์ด

import java.util.*;

class Solution {
    public int[] solution(int n, String[] words) {
        int[] answer = {0, 0};
        Map<String, Integer> map = new HashMap<>();

        for(int i=0; i<words.length; i++){
            if(i!=0){
                String prev = words[i-1];
                String curr = words[i];

                char last = prev.charAt(prev.length() - 1);
                char first = curr.charAt(0);

                if(map.containsKey(curr) || last != first){
                    answer[0] = (i % n) + 1;
                    answer[1] = (i / n) + 1;

                    return answer;
                }
            }
            map.put(words[i], 1);
        }
        return answer;
    }
}

์ด ๋ฌธ์ œ๋Š” Map ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ฒ˜์Œ์—๋Š” ์Šคํƒ์— ๋ชจ๋“  ๊ฐ’์„ ๋„ฃ๊ณ  ์ผ์ผ์ด ๋น„๊ตํ•˜๋ ค๊ณ  ํ•˜์˜€์œผ๋‚˜ ํšจ์œจ์ ์ด์ง€ ์•Š๊ณ  ์ค‘๋ณต์ฒดํฌ๋ฅผ ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— Map์„ ์ด์šฉํ•˜์˜€๋‹ค. 

 

1. ์ด์ „ ๋‹จ์–ด๋ฅผ prev, ํ˜„์žฌ ๋‹จ์–ด๋ฅผ curr์— ์ €์žฅํ•œ๋‹ค. 

2. ์ด์ „ ๋‹จ์–ด์˜ ๋งˆ์ง€๋ง‰ ๋ฌธ์ž๋ฅผ last, ํ˜„์žฌ ๋‹จ์–ด์˜ ์ฒซ๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ first์— ์ €์žฅ

3. ๋งŒ์•ฝ ํ˜„์žฌ ๋‹จ์–ด๊ฐ€ map์— ์žˆ์„ ๊ฒฝ์šฐ ๋˜๋Š” ๋งˆ์ง€๋ง‰ ๋ฌธ์ž์™€ ํ˜„์žฌ์˜ ์ฒซ๋ฒˆ์งธ ๋ฌธ์ž๊ฐ€ ๊ฐ™์ง€ ์•Š์„ ๊ฒฝ์šฐ ํƒˆ๋ฝ์ด๋ฏ€๋กœ return ํ•ด์ค€๋‹ค. 

4. ๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ map์— ํ˜„์žฌ์˜ ๋‹จ์–ด๋ฅผ putํ•˜๊ณ  ๋‹ค์Œ์œผ๋กœ ๋„˜์–ด๊ฐ„๋‹ค. 

 

์ตœ์ข…์ ์œผ๋กœ ๋ชจ๋“  words๋ฅผ ๋Œ์•˜์„ ๋•Œ ์‹คํŒจํ•˜์ง€ ์•Š์œผ๋ฉด ์ฒ˜์Œ answer๋ฅผ ์ดˆ๊ธฐํ™” ํ–ˆ๋˜ [0,0]์ด ๋ฐ˜ํ™˜๋˜๊ณ  ์ค‘๊ฐ„์— ์‹คํŒจํ•  ๊ฒฝ์šฐ answer๊ฐ€ ๋ฐ˜ํ™˜๋œ๋‹ค. 

 

map๋ง๊ณ  set์ด๋‚˜ ๋‹ค๋ฅธ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ’€์ด๋ฅผ ํ•  ์ˆ˜๋„ ์žˆ์œผ๋ฏ€๋กœ ์ฐธ๊ณ ํ•˜๊ธฐ ๋ฐ”๋ž€๋‹ค.