Java

프로그래머스: 영어 끝말잇기

Daeryuk Kim 2024. 3. 5. 22:33
import java.util.*;

class Solution {
    public int[] solution(int n, String[] words) {
        int[] answer = new int[2];
        ArrayList<String> usedWords = new ArrayList<>();
        
        for (int i=0; i<words.length; i++) {
        	// 이전 단어의 끝 단어가 현재 단어의 첫 단어랑 같지 않은가 
            if (i > 0 && words[i-1].charAt(words[i-1].length()-1) != words[i].charAt(0)) {
                answer[0] = i % n + 1;
                answer[1] = i / n + 1;
                break;
            }
            // 이전에 부른 단어를 또 부르진 않았는가
            if (usedWords.contains(words[i])) {
                answer[0] = i % n + 1;
                answer[1] = i / n + 1;
                break;
            } else {
                usedWords.add(words[i]);
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        int n = 3;
        String[] words = {"tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"};
        Solution sol = new Solution();
        int[] result = sol.solution(n, words);
        System.out.println(Arrays.toString(result)); 
    }
}

ArrayList를 사용하면 이렇게 빨리 풀 수 있는데 괜히 배열만 늘리다가 포기했다. ㅠㅠ

contains()랑 add()를 쓰니까 이렇게 간결한 코드가 되었다.