Leetcode 953. Verifying an Alien Dictionary with Python

Alpha, Orderly·2023년 2월 2일
0

leetcode

목록 보기
42/90
post-thumbnail

문제

In an alien language, surprisingly, they also use English lowercase letters, 
but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, 
return true if and only if the given words are sorted lexicographically in this alien language.

놀랍게 외계인의 언어도 영어의 소문자를 사용한다!
그들은 알파벳의 순서만 다르게 하여 영어를 사용하는데,
당신에게 여러개의 단어 목록과 외계어의 알파벳이 주어질때,
주어진 단어의 목록이 사전적으로 완벽하게 정렬되어 있는지를 확인 후 리턴하시오.

예시

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: 사전적으로 완벽하게 정렬됨.
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: word 와 world의 네번째 문자인 d와 l에서 l이 앞서기에 순서가 바뀌어야 한다.

제한

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • order.length == 26
  • All characters in words[i] and order are English lowercase letters.

풀이법

sorted를 호출시 key에 cmp_to_key 함수를 이용해 정렬 함수를 호출할수 있다

이를 이용해 해결하면 된다.

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        characterOrder = dict()
        i = 0
        for ch in order:
            characterOrder[ch] = i
            i += 1
        def compare(a, b):
            for i in range(len(a) if len(a) < len(b) else len(b)):
                if a[i] != b[i]:
                    return characterOrder[a[i]] - characterOrder[b[i]]
            return len(a) - len(b)
        std = sorted(words, key=cmp_to_key(compare))
        
        if len(std) != len(words): return False
        for i in range(len(std)):
            if std[i] != words[i]: return False
        return True
profile
만능 컴덕후 겸 번지 팬

0개의 댓글