• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

剑指 Offer II 034. 外星语言是否排序

武飞扬头像
感觉画质不如…原神
帮助1

题目链接

剑指 Offer II 034. 外星语言是否排序 easy

题目描述

某种外星语也使用英文小写字母,但可能顺序 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 < = w o r d s . l e n g t h < = 100 1 <= words.length <= 100 1<=words.length<=100
  • 1 < = w o r d s [ i ] . l e n g t h < = 20 1 <= words[i].length <= 20 1<=words[i].length<=20
  • o r d e r . l e n g t h = = 26 order.length == 26 order.length==26
  • words[i]order中的所有字符都是英文小写字母。

解法:哈希表

用哈希表 m记录 ordera ~ z得映射,比如 order = "hlabcdefgijkmnopqrstuvwxyz",那么 m['h'] = 'a' , m['i'] = 'b'

pre表示上一个已经转换过的 word,这时的word代表当前 word。我们先将当前的 word根据 m的映射进行转换。

如果 pre > word,说明 words不是按给定的字典序排序的,返回 false

遍历完成说明 words是按照给定字典序排序的,那么返回 true

时间复杂度: O ( m ∗ n ) O(m * n) O(mn)

C 代码:

class Solution {
public:
    bool isAlienSorted(vector<string>& words, string order) {
        unordered_map<char,char> m;
        for(int i = 0;i < order.size();i  ){
            m[order[i]] = i   'a';
        }

        string pre;
        for(auto word:words){
            int n = word.size();
            for(int i = 0;i < n;i  ){
                word[i] = m[word[i]];
            }
            if(pre > word) return false;
            pre = word;
        }

        return true;
    }
};

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgagekh
系列文章
更多 icon
同类精品
更多 icon
继续加载