LeetCode 953 Verifying an Alien Dictionary 解题报告

时间:2024-11-16 09:35:49

题目要求

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

题目分析及思路

给定一组字符串以及一个字母表顺序,判断这组字符串是否是按照给定字母表顺序排列的。可以对该组字符串进行两两比较,依据最短字符串长度分别遍历两个字符串。若前者的字符顺序小于后者的,则跳出循环,继续比较其他字符串;若前者的字符顺序大于后者的,则返回False;若相等则继续比较,直到所有字符都相等,若较长字符串在前则返回False。

python代码

class Solution:

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

for idx in range(1, len(words)):

len_min = min(len(words[idx-1]), len(words[idx]))

flag = 0

while len_min:

if order.index(words[idx-1][flag]) < order.index(words[idx][flag]):

break

elif order.index(words[idx-1][flag]) > order.index(words[idx][flag]):

return False

len_min -= 1

flag += 1

if len_min == 0 and len(words[idx-1]) > len(words[idx]):

return False

return True