LEETCODE | PYTHON | 953 | 验证外星语单词

该问题涉及字符串处理和排序算法,给定一个外星语单词列表和字母表顺序,程序需判断单词是否按字典序排列。通过逐个比较相邻单词的首不同字母在定制字母表中的位置来决定顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LEETCODE | PYTHON | 953 | 验证外星语单词

1. 题目

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/verifying-an-alien-dictionary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 代码

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:

        #words = ["world","world","row"]

        #遍历单词判断
        for i in range(1,len(words)):

            index = 0

            #找到当前单词与前一单词首个不同的字母
            while index < min(len(words[i-1]),len(words[i])) and words[i-1][index] == words[i][index]:
                index = index + 1
            
            #判断两单词剩余长度
            #两者都为0,则两单词相同,continue
            if len(words[i-1]) == index and len(words[i]) == index:
                #print('situation1')
                continue

            #若后者比前者长则continue
            elif len(words[i-1]) == index:
                #print('situation2')
                continue

            #若前者比后者长,则False
            elif len(words[i]) == index:
                #print('situation3')
                return False

            #两者都有剩余则比较不同单词
            else:
                #print('situation4')
                #比较字母大小
                pos1 = order.find(words[i-1][index])
                pos2 = order.find(words[i][index])
                #print(index,pos1,pos2)
                if pos1 > pos2:
                    return False

        return True
                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值