Leetcode-Easy 953. Verifying an Alien Dictionary

题目描述

给定一组单词和字母顺序,然后判断单词之间是否按字典序顺序排序。

字典序的理解:
设想一本英语字典里的单词,哪个在前哪个在后?
显然的做法是先按照第一个字母、以 a、b、c……z 的顺序排列;如果第一个字母一样,那么比较第二个、第三个乃至后面的字母。如果比到最后两个单词不一样长(比如,sigh 和 sight),那么把短者排在前。

Example 1:

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).

思路

创建一个字典序,代表每个字母的大小。然后将单词的排序转换为数字字符串排序:
比如'00'<'01','22'<'23'等

代码实现

class Solution:
    def isAlienSorted(self, words: 'List[str]', order: 'str') -> 'bool':
        ld=dict()
        for i in range(25,-1,-1):
            if i<10:
                ld[order[25-i]]='0'+str(i)
            else:
                ld[order[25-i]]=str(i)
        # print(ld)        
        for i in range(len(words)-1):
            lw,rw='',''
            for l in words[i]:
                lw=lw+str(ld[l])
            for l in words[i+1]:
                rw=rw+str(ld[l])
            lw=lw+(20-len(lw))*'9'
            rw=rw+(20-len(rw))*'9'
            # print(lw,rw)
            if lw<rw:
                return False
        return True

其他解法

自己写的运行效率还可以36ms,超过99.7%。然后去讨论区看了下大佬写的,顿时给跪了,思路差不多,但是简洁多了:

class Solution:
    def isAlienSorted(self, words, order):
        m = {c: i for i, c in enumerate(order)}
        words = [[m[c] for c in w] for w in words]
        return all(w1 <= w2 for w1, w2 in zip(words, words[1:]))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值