LeetCode 题解工作台

验证外星语词典

某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序( order )是一些小写字母的排列。 给定一组用外星语书写的单词 words ,以及其字母表的顺序 order ,只有当给定的单词在这种外星语中按字典序排列时,返回 true ;否则,返回 false 。 示例 1: 输入:…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

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

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

某种外星语也使用英文小写字母,但可能顺序 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 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • order.length == 26
  • 在 words[i] 和 order 中的所有字符都是英文小写字母。
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        m = {c: i for i, c in enumerate(order)}
        for i in range(20):
            prev = -1
            valid = True
            for x in words:
                curr = -1 if i >= len(x) else m[x[i]]
                if prev > curr:
                    return False
                if prev == curr:
                    valid = False
                prev = curr
            if valid:
                return True
        return True
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Is the candidate able to efficiently map the alien alphabet?

  • question_mark

    Can they identify and handle edge cases such as prefix issues?

  • question_mark

    Does the candidate approach the problem with an array scanning and hash table solution, avoiding unnecessary complexity?

warning

常见陷阱

外企场景
  • error

    Not properly handling cases where a word is a prefix of another (e.g., 'apple' vs 'app').

  • error

    Failing to correctly implement the lexicographical comparison using the alien alphabet's custom order.

  • error

    Overcomplicating the solution by not recognizing the optimal approach using array scanning and hash lookups.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the list of words is very large? Can the algorithm still scale efficiently?

  • arrow_right_alt

    How would the solution change if we were given words in reverse order?

  • arrow_right_alt

    Can we solve the problem without using a hash table, and if so, what would the time complexity be?

help

常见问题

外企场景

验证外星语词典题解:数组·哈希·扫描 | LeetCode #953 简单