验证外星语词典(来源力扣)

某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。

给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。

示例 1:
输入:words = [“hello”,“leetcode”], order = “hlabcdefgijkmnopqrstuvwxyz”
输出:true
解释:在该语言的字母表中,‘h’ 位于 ‘l’ 之前,所以单词序列是按字典序排列的。

示例 2:
输入:words = [“word”,“world”,“row”], order = “worldabcefghijkmnpqstuvxyz”
输出:false
解释:在该语言的字母表中,‘d’ 位于 ‘l’ 之后,那么 words[0] > words[1],因此单词序列不是按字典序排列的。

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        list = [0] * 26
        for i in range(26):
            list[ord(order[i]) - ord('a')] = i
        for i in range(1, len(words)):
            j = 0
            flag = False
            while j < len(words[i - 1]) and j < len(words[i]):
                idx1 = list[ord(words[i - 1][j]) - ord('a')]
                idx2 = list[ord(words[i][j]) - ord('a')]
                if idx1 < idx2:
                    flag = True
                    break
                elif idx1 > idx2:
                    return False
                j += 1
            if not flag:
                if len(words[i - 1]) > len(words[i]):
                    return False
            i += 1
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值