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