1. 程式人生 > >【Leetcode_總結】 953. 驗證外星語詞典 - python

【Leetcode_總結】 953. 驗證外星語詞典 - python

Q:

某種外星語也使用英文小寫字母,但可能順序 order 不同。字母表的順序(order)是一些小寫字母的排列。

給定一組用外星語書寫的單詞 words,以及其字母表的順序 order,只有當給定的單詞在這種外星語中按字典序排列時,返回 true;否則,返回 false

示例 1:

輸入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
輸出:true
解釋:在該語言的字母表中,'h' 位於 'l' 之前,所以單詞序列是按字典序排列的。

示例 2:

輸入:words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
輸出:false
解釋:在該語言的字母表中,'d' 位於 'l' 之後,那麼 words[0] > words[1],因此單詞序列不是按字典序排列的。

示例 3:

輸入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
輸出:false
解釋:當前三個字元 "app" 匹配時,第二個字串相對短一些,然後根據詞典編纂規則 "apple" > "app",因為 'l' > '∅',其中 '∅' 是空白字

連結:https://leetcode-cn.com/problems/verifying-an-alien-dictionary/description/

思路:首先建立一個字典用於記錄順序,對於一個字典序問題,開始的思路是直接比較全部的首字母,但是發現實現起來並不容易,然後就兩個兩個的比較,因此定義了check函式,然後通過該函式比較兩個單詞是否符合字典序的要求,由於使用了zip函式,加之單詞之間的長度不同,因此對單詞使用“#”進行了填充,並將#設定為最大值,便可解決示例3中的情況,程式碼如下:

程式碼:

class Solution:
    def isAlienSorted(self, words, order):
        """
        :type words: List[str]
        :type order: str
        :rtype: bool
        """
        order+="#"
        dic = {}
        for i in range(len(order)):
            dic[order[i]] = i
        for i in range(len(words)-1):
            if self.check(words[i], words[i+1],dic):
                pass
            else:
                return False
        return True

    def check(self,words1,words2,dic):
        max_ = max(len(words1), len(words2))
        words1 = words1 + (max_- len(words1))* '#'
        words2 = words2 + (max_ - len(words1)) * '#'
        temp = list(zip(words1,words2))
        i = 0
        while i < (len(temp)):
            if temp[i][0] != temp[i][1]:
                if dic[temp[i][0]] < dic[temp[i][1]]:
                    return True
                else:
                    return False
            i+=1