Description:
In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words 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.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
Note:
- 1 <= words.length <= 100
- 1 <= words[i].length <= 20
- order.length == 26
- All characters in words[i] and order are english lowercase letters.
题意:给定一个单词列表words,里面包含了一定数量的字符串,根据另外给定的一个字符顺序表(位置越靠后表示越大),判断words单词列表中的字符串是否是非降序排序的;
解法:我们需要解决的就是如何比较两个字符串;根据给定的字母顺序表,相当于我们重新定义了每个字母的ascll码,这里可以使用哈希表来存储;之后,我们根据构造的哈希表定义自己的字符串比较函数,对相邻的两个字符串进行比较,判断是否为非降序的;
Java
class Solution {
public boolean isAlienSorted(String[] words, String order) {
Map<Character, Integer> table = new HashMap<>();
for (int i = 0; i < order.length(); i++) {
table.put(order.charAt(i), i);
}
for (int i = 1; i < words.length; i++) {
if (compareStr(words[i - 1], words[i], table) != -1) {
return false;
}
}
return true;
}
private int compareStr(String str1, String str2,
Map<Character, Integer> table) {
int ind1 = 0;
int ind2 = 0;
while (ind1 < str1.length() && ind2 < str2.length()) {
if (table.get(str1.charAt(ind1)) < table.get(str2.charAt(ind2))) return -1;
if (table.get(str1.charAt(ind1)) > table.get(str2.charAt(ind2))) return 1;
ind1++;
ind2++;
}
if (str1.length() == str2.length()) return 0;
return str1.length() > str2.length() ? 1 : -1;
}
}