1876. 外星人字典(简单)

1876. 外星人字典(简单)

中文English

某种外星语也使用英文小写字母,但可能顺序 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' > '∅',其中 '∅' 是空白字符,定义为比任何其他字符都小(更多信息)。

说明

  1. 1 <= words.length <= 100
  2. 1 <= words[i].length <= 20
  3. order.length == 26
  4. 在 words[i] 和 order 中的所有字符都是英文小写字母。
class Solution:
    '''
    大致思路:
    1.循环单词,如果当前单词的下一个只要出现大于当前单词的,直接break,说明符合条件。否则的话,看是否出现在order里index顺序不符合的,如果
    有,则返回False。最后还需要判断,当出现apple,app类似这种情况,前面均符合,后面下一个值没有,则也是false。否则True
    '''
    def  isAlienSorted(self, words, order):
        for i in range(len(words)-1):
            l = len(words[i]) if len(words[i]) <= len(words[i+1]) else len(words[i+1])

            for j in range(l):
                if order.index(words[i][j]) < order.index(words[i+1][j]):
                    break
                elif order.index(words[i][j]) > order.index(words[i+1][j]):
                    return False
            
            if words[i][:l] == words[i+1][:l]:
                if len(words[i+1]) < len(words[i]):
                    return False
        return True

 

posted @ 2020-05-02 23:33  风不再来  阅读(457)  评论(0编辑  收藏  举报