力扣剑指Offer II 034. 外星语言是否排序

这样的解法,可以通过,

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        
        def cmp(ls1, ls2):
            n = min(len(ls1), len(ls2))
            i = 0
            while i < n and ls1[i] == ls2[i]:
                i += 1
            
            if i == n:
                if len(ls1) == n:
                    return True
                else:
                    return False
            else:
                index1 = order.index(ls1[i])
                index2 = order.index(ls2[i])
                if index1 < index2:
                    return True
                else:  #已经不存在index1 == index2的情况
                    return False
                    
        n = len(words)
        for i in range(n-1):
            if cmp(words[i],words[i+1]) == False:
                return False
        return True

但如果我想要对列表words进行排序时,结果却是通不过,

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        
        def cmp(ls1, ls2):
            n = min(len(ls1), len(ls2))
            i = 0
            while i < n and ls1[i] == ls2[i]:
                i += 1
            
            if i == n:
                if len(ls1) == n:
                    return True
                else:
                    return False
            else:
                index1 = order.index(ls1[i])
                index2 = order.index(ls2[i])
                if index1 < index2:
                    return True
                else:  #已经不存在index1 == index2的情况
                    return False

        words_sorted = sorted(words, key = functools.cmp_to_key(cmp))

        if words_sorted == words:
            return True
        else:
            return False

先贴在这里,回头再来解决!!!

上一篇:leetcode 541. 反转字符串 II


下一篇:数据结构--排序之归并排序