题目
某种外星语也使用英文小写字母,但可能顺序 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 中的所有字符都是英文小写字母。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/verifying-an-alien-dictionary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
使用哈希表或者数组记录order中的字母先后顺序,然后遍历words数组两两比较就行了。
代码
class Solution {public boolean isAlienSorted(String[] words, String order) {Map<Character, Integer> map = new HashMap<>();for (int i = 0; i < order.length(); i++) {map.put(order.charAt(i), i);}for (int i = 1; i < words.length; i++) {int p = 0;int q = 0;// 比较words[i - 1]和words[i]while (p < words[i - 1].length() && q < words[i].length()) {int a = map.get(words[i].charAt(q));int b = map.get(words[i - 1].charAt(p));// 当前字符串字典序小,直接返回falseif (a < b) {return false;}// 当前的字符串的字典序大,后面的字符没必要看了if (a > b) {break;}p++;q++;}// 特殊情况,如果两个字符串遍历结束了,前一个字符串还有多于字符,也要返回falseif (p < words[i - 1].length() && q == words[i].length()) {return false;}}return true;}}
py
python的一行写法,学习一下
class Solution:def isAlienSorted(self, words: List[str], order: str) -> bool:return words == sorted(words, key=lambda w: [order.index(c) for c in w])
使用dict存储字符在order中的位次,不用每次去搜索
class Solution:def isAlienSorted(self, words: List[str], order: str) -> bool:map = {c: i for i, c in enumerate(order)}return words == sorted(words, key=lambda w: [map[c] for c in w])
