코딩테스트 연습 - 영어 끝말잇기 | 프로그래머스 스쿨 (programmers.co.kr)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const solution = (n, words) => { | |
const notfailed = [0, 0]; | |
const set = new Set(); | |
for (let i = 0; i < words.length; i++) { | |
const word = words[i]; | |
const identifiedPerson = (i % n) + 1; | |
const gameTurn = Math.ceil((i + 1) / n); | |
if (i > 0 && words[i - 1].slice(-1) !== words[i][0]) { | |
return [identifiedPerson, gameTurn]; | |
} | |
if (!set.has(word)) { | |
set.add(word); | |
} else { | |
return [identifiedPerson, gameTurn]; | |
} | |
} | |
return notfailed; | |
}; |
HashSet 사용
시간 복잡도 O(n)
설명)
1. && 연산자는 순서대로 판별하기 때문에 if 문 내 i > 0 조건이 뒤로 배치된다면 오류남
2. string 마지막 글자 가져오는 법) 총 길이 - 1 인덱스로 가져오거나 아니면 slice(-1) 로 가져올 수 있음
3. 조건 대로 분기점 처리 잘 해주면 됨
4. 문제에서 원하는 답을 계산하는 간단한 규칙 알면 됨
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스 Lv.3] 여행경로: JavaScript 알고리즘 풀이 with DFS (Feat. 얕복 깊복 이슈) (2) | 2024.01.27 |
---|---|
[프로그래머스 Lv. 2] 다음 큰 숫자 - 비트연산자 사용한 시간 복잡도 O(1) JavaScript 풀이 (0) | 2022.12.08 |
[프로그래머스 Lv 2] 행렬의 곱셈 JavaScript 풀이 (0) | 2022.12.05 |
[프로그래머스 Lv 2] 카펫 JavaScript 풀이 (0) | 2022.12.03 |
[프로그래머스 Lv 2] JadenCase 문자열 만들기 JavaScript 풀이 (0) | 2022.12.02 |