Leetcode-Easy 953. Verifying an Alien Dictionary

简介: 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:]))


相关文章
|
Java
[LeetCode] Alien Dictionary
Problem Description: There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you.
891 0
|
7月前
|
存储 Swift
在Swift编程语言中,字典(Dictionary)
在Swift编程语言中,字典(Dictionary)
85 3
|
存储 Java Python
多重字典(Multi-Level Dictionary)
多重字典(Multi-Level Dictionary)是一种将多个字典组合在一起的数据结构,用于解决需要在多个维度上查找数据的问题。多重字典可以看作是一个嵌套的字典,每个字典都可以作为其他字典的键。 使用多重字典的场景:
177 3
|
7月前
|
存储 缓存 数据库连接
Python基础教程——字典(Dictionary)
Python基础教程——字典(Dictionary)
|
6月前
|
存储 Python 容器
|
6月前
|
Python 存储 容器
Python 字典(Dictionary)
Python 字典(Dictionary)