领扣LintCode算法问题答案-1876. 外星人字典(简单)
目录
1876. 外星人字典(简单)描述样例 1:样例 2:样例 3:
题解鸣谢
1876. 外星人字典(简单)
描述
某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。
1 <= words.length <= 1001 <= words[i].length <= 20order.length == 26在 words[i] 和 order 中的所有字符都是英文小写字母。
样例 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' > '∅',其中 '∅' 是空白字符,定义为比任何其他字符都小(更多信息)。
题解
public class Solution {
public boolean isAlienSorted(String
[] words
, String order
) {
Map
<Character, Integer> orders
= new HashMap<>();
for (int i
= 0; i
< order
.length(); i
++) {
orders
.put(order
.charAt(i
), i
);
}
for (int i
= 0; i
< words
.length
- 1; i
++) {
String word1
= words
[i
];
String word2
= words
[i
+ 1];
for (int j
= 0; j
< Math
.min(word1
.length(), word2
.length()); j
++) {
char c1
= word1
.charAt(j
);
char c2
= word2
.charAt(j
);
int o1
= orders
.get(c1
);
int o2
= orders
.get(c2
);
if (o1
< o2
) {
break;
}
if (o1
> o2
) {
return false;
}
}
}
return true;
}
}
原题链接点这里
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。