😎풀이

  1. words의 각 단어 Set에 추가
  2. words를 길이를 기준으로 오름차 순 정렬하며 동일한 길이인 경우 사전순 내림차 순 정렬
  3. 가장 길면서 사전순 가장 빠른 요소부터 모든 글자를 완성시킬 수 있는지 검증 후 가능하다면 즉시 반환
  4. 모든 요소가 완성 불가하다면, 빈 문자열 반환
function longestWord(words: string[]): string {
    const set = new Set<string>()
    for(const word of words) set.add(word)
    const sorted = words.toSorted((a, b) => {
        if(a.length !== b.length) return a.length - b.length
        return b.localeCompare(a)
    })
    for(let i = sorted.length - 1; i >= 0; i--) {
        const word = sorted[i]
        let canBuild = true
        for(let j = 1; j <= word.length; j++) {
            const sliced = word.slice(0, j)
            if(set.has(sliced)) continue
            canBuild = false
            break
        }
        if(canBuild) return word
    }
    return ""
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글