In an alien language, surprisingly they also use english lowercase letters, but possibly in a differentorder
. The order
of the alphabet is some permutation of lowercase letters.
Given a sequence ofwords
written in the alien language, and theorder
of the alphabet, returntrue
if and only if the givenwords
are sorted lexicographicaly in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
按照order记录每个字符的位置,比较相邻的两个字符串,第一个不同的字符位置,应该满足前一个字符串中的字符在后一个字符串中的字符之前,如果在合法范围内找不到不同的字符,则第一个字符串必须比第二个字符串短
class Solution {
public boolean isAlienSorted(String[] words, String order) {
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < order.length(); i++) {
map.put(order.charAt(i), i);
}
for(int i = 0; i < words.length - 1; i++) {
String str1 = words[i];
String str2 = words[i + 1];
int j = 0;
for(; j < Math.min(str1.length(), str2.length()); j++) {
if(str1.charAt(j) != str2.charAt(j)) {
if(map.get(str1.charAt(j)) > map.get(str2.charAt(j)))
return false;
break;
}
}
if(j == Math.min(str1.length(), str2.length()) && str1.length() > str2.length())
return false;
}
return true;
}
}