首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode-Easy 953. Verifying an Alien Dictionary

Leetcode-Easy 953. Verifying an Alien Dictionary

作者头像
致Great
发布2019-03-13 15:46:54
5870
发布2019-03-13 15:46:54
举报
文章被收录于专栏:程序生活程序生活

题目描述

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

字典序的理解: 设想一本英语字典里的单词,哪个在前哪个在后? 显然的做法是先按照第一个字母、以 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:]))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.02.19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路
  • 代码实现
  • 其他解法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档