美文网首页
Leetcode-Easy 953. Verifying an

Leetcode-Easy 953. Verifying an

作者: 致Great | 来源:发表于2019-02-19 09:42 被阅读7次

    题目描述

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

    字典序的理解:
    设想一本英语字典里的单词,哪个在前哪个在后?
    显然的做法是先按照第一个字母、以 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:]))
    

    相关文章

      网友评论

          本文标题:Leetcode-Easy 953. Verifying an

          本文链接:https://www.haomeiwen.com/subject/knzaeqtx.html