본문 바로가기

알고리즘 문제풀이

[프로그래머스 12981] Level2 영어 끝말잇기(Java)

문제 URL

https://school.programmers.co.kr/learn/courses/30/lessons/12981

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제풀이 Key Point

  • 이전에 말한 단어의 끝 알파벳과 현재 말하는 단어의 앞 알파벳이 일치해야한다.
  • 이전까지 말한 단어를 중복해서 말하면 안된다.

 

Java 문제풀이

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
 
class Solution {
    public int[] solution(int n, String[] words) {
        int[] answer = new int[2];
 
        Map<Integer, Integer> players = new HashMap<>();
        Set<String> wordGroup = new HashSet<>();
        
        for (int i = 0; i < n; i++) {
            players.put(i + 10);
        }
        
        boolean prevWord = false;
        String lastAlphabet = "";
        String currentAlphabet = "";
        int turn = 1;
        for (String word : words) {
            players.put(turn, players.get(turn) + 1);
            
            currentAlphabet = word.substring(01);
            if (prevWord) {
                if (!lastAlphabet.equals(currentAlphabet)) {
                    return new int[]{turn, players.get(turn)};
                }
            }
            
            if (wordGroup.contains(word)) {
                return new int[]{turn, players.get(turn)};
            }
            wordGroup.add(word);
            lastAlphabet = word.substring(word.length() - 1);
            prevWord = true;
            turn++;
            
            if (turn > n) {
                turn = 1;
            }
        }
 
        return answer;
    }
}
 
cs