【LeetCode】953. 验证外星语词典

148 阅读1分钟

image.png

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。

怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

image.png

  • 题目示例

image.png

  • 题目解析

    • 1 <= words.length <= 100
    • 1 <= words[i].length <= 20
    • order.length == 26
    • 在 words[i] 和 order 中的所有字符都是英文小写字母。

二、思路分析:

我们拿到本题,读取题意要求我们检查列表words中的单词排序是按照指定的字典序order顺序排序,如果是则返回True,反之则返回False。

关于字典序,我们前面也刷到过关于字典序排序的题如386.字典序排序中,get到字典序排列概念:

  • 字典序排序:先按第一位排序,第一位排序完成后再排第二位,依次类推
  • 字典序排列特点:前一位的顺序一定小于后一位的顺序位置

image.png

对字典序排序的特点,排序顺序是按照a~z或者0-9,但是本题是需要指定 order 字符串顺序

  • 根据 order 字符串,使用dictionary转换成字符与索引映射关系
  • key=字符,value=index

因此解决本题,我们需要借助两个指针来遍历列表words元素,解答该题的思路如下:

  • 使用for循环遍历Words列表,并且定义pre,after前后指针
  • 当 pre字符串 与 after字符串 相同时,则Words列表继续往右+1
  • 当 pre字符串 与 after字符串 取较短的长度__len()
  • 遍历 pre 与 after 字符串中,取出dictionary字典中字符的索引位置进行比较
  • 当 dictionary[pre[j]] 大于 dictionary[after[j]],则不符合Oder排序,返回False
  • 当 dictionary[pre[j]] 小于 dictionary[after[j]], 则退出当前遍历查找
  • 判断len(pre)大于len(after) 并且 pre[:__len()] == after,则返回False

通过上述思路,我们使用Python可以实现,代码如下:

class Solution(object):
    def isAlienSorted(self, words, order):
        """
        :type words: List[str]
        :type order: str
        :rtype: bool
        """
        dictionary = {}
        for i,c in enumerate(order):
            dictionary[c] = i
        for i in range(len(words)-1):
            pre,after =words[i],words[i+1]
            if pre == after: continue
            _len = min(len(pre),len(after))
            for j in range(_len):
                if dictionary[pre[j]] < dictionary[after[j]]:
                    break   
                elif dictionary[pre[j]] > dictionary[after[j]]:
                    return False      
            if len(pre) > len(after) and pre[:_len] == after:
                return False
        return True

三、总结:

本题仍然考察我们哈希映射表的关系,通过哈希表把字符和索引位置进行关联,在后续判断中就能通过索引位置来进行判断,AC提交记录如下:

image.png

  • 时间复杂度O(M*N)
  • 空间复杂度O(1)

以上是本期内容,欢迎大佬们点赞评论,下期见~~~