Q:
某种外星语也使用英文小写字母,但可能顺序 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],因此单词序列不是按字典序排列的。
示例 3:
输入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" 输出:false 解释:当前三个字符 "app" 匹配时,第二个字符串相对短一些,然后根据词典编纂规则 "apple" > "app",因为 'l' > '∅',其中 '∅' 是空白字
链接:https://leetcode-cn.com/problems/verifying-an-alien-dictionary/description/
思路:首先建立一个字典用于记录顺序,对于一个字典序问题,开始的思路是直接比较全部的首字母,但是发现实现起来并不容易,然后就两个两个的比较,因此定义了check函数,然后通过该函数比较两个单词是否符合字典序的要求,由于使用了zip函数,加之单词之间的长度不同,因此对单词使用“#”进行了填充,并将#设置为最大值,便可解决示例3中的情况,代码如下:
代码:
class Solution:
def isAlienSorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
order+="#"
dic = {}
for i in range(len(order)):
dic[order[i]] = i
for i in range(len(words)-1):
if self.check(words[i], words[i+1],dic):
pass
else:
return False
return True
def check(self,words1,words2,dic):
max_ = max(len(words1), len(words2))
words1 = words1 + (max_- len(words1))* '#'
words2 = words2 + (max_ - len(words1)) * '#'
temp = list(zip(words1,words2))
i = 0
while i < (len(temp)):
if temp[i][0] != temp[i][1]:
if dic[temp[i][0]] < dic[temp[i][1]]:
return True
else:
return False
i+=1