문자열 배열 words 가 주어지고 특별한 스펠링 순서인 order가 주어질 때 words가 사전식 순서로 정렬되어 있으면 true를 , 아니라면 false를 리턴하는 문제이다.
Example을 보자
3번 예시와 같이 빈칸의 경우는 어떤 문자보다 작다고 하였으므로 길이에 대한 조건도 추가해주어야한다.
const isAlienSorted = function (words, order) {
let current = 0
let next = 0
for (let i=0; i < words.length-1; i++) {
current = order.indexOf(words[i][0]) // 현재 단어의 첫번째 문자
next = order.indexOf(words[i+1][0]) // 다음 단어의 첫번째 문자
if (current < next) continue; // 사전순이 맞으므로 continue
else if (current > next) return false; // 사전순이 아니므로 false
else if (current === next) { // 그 다음 문자 비교
for (let j = 1; j < Math.min(words[i].length, words[i+1].length); j++) {
current = order.indexOf(words[i][j])
next = order.indexOf(words[i+1][j])
if (current < next) continue; // 사전순이 맞으므로 continue
else if (current > next) return false; // 사전순이 아니므로 false
}
if (words[i].length > words[i+1].length && current===next) return false;
}
}
return true;
};
submit을 해보니
정답이었다!