본문 바로가기

Algorithm/프로그래머스

[프로그래머스] 영어 끝말잇기 - Java

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

 

코딩테스트 연습 - 영어 끝말잇기

3 [tank, kick, know, wheel, land, dream, mother, robot, tank] [3,3] 5 [hello, observe, effect, take, either, recognize, encourage, ensure, establish, hang, gather, refer, reference, estimate, executive] [0,0]

programmers.co.kr

import java.util.HashSet;

class Solution {
    public int[] solution(int n, String[] words) {
        int[] answer = new int[2];
        HashSet<String> s = new HashSet<>();

        s.add(words[0]);

        int i;
        for (i = 1; i < words.length; i++) {
            if (s.contains(words[i])) break;
            if (words[i].charAt(0) != words[i-1].charAt(words[i-1].length() - 1)) break;
            s.add(words[i]);
        }

        if (i == words.length) {
            return answer;
        }

        answer[0] = i % n + 1;
        answer[1] = i / n + 1;

        return answer;
    }
}