力扣题解:953. 验证外星语词典

95 阅读1分钟

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

题目描述

原题链接 :

953. 验证外星语词典 - 力扣(LeetCode)

某种外星语也使用英文小写字母,但可能顺序 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 中的所有字符都是英文小写字母。

思路分析

和第一题twoSum的原理差不多,建立索引来查位置。
第一步,先建立一个索引的键值对,key是字母表中的字母,value是字母在字母表中的顺序,这里建立索引可以用一个数组,也可以用Map;
第二步,写一个单词比较的函数,遍历字符串中的每个字符,根据第一步中的索引来查询字符在字母表中的顺序,顺序的大小即为字符的大小;
第三步,遍历单词,比较每个单词的大小;

AC 代码

class Solution {
    public boolean isAlienSorted(String[] words, String order) {
        int[] dict = new int[order.length()];
        for (int i = 0; i < order.length(); i++) {
            dict[order.charAt(i) - 'a'] = i;
        }
        for (int i = 1; i < words.length; i++) {
            if (compare(words[i - 1], words[i], dict) > 0) {
                return false;
            }
        }
        return true;
    }

    public int compare(String s1, String s2, int[] dict) {
        int a, b;
        for (int i = 0; i < s1.length() || i < s2.length(); i++) {
            a = i < s1.length() ? dict[s1.charAt(i) - 'a'] : -1;
            b = i < s2.length() ? dict[s2.charAt(i) - 'a'] : -1;
            if (a < b) {
                return - 1;
            } else if (a > b) {
                return 1;
            }
        }
        return 0;
    }
}