953. Verifying an Alien Dictionary - Easy
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]
andorder
are english lowercase letters.
把order中每个字母及其次序用hashmap表示,因为order的长度是已知且固定的,可以用数组代替hashmap,用 对应的字符 - a 表示该字符
然后遍历words,分别比较每一个字符串与前一个字符串
compare details: 比较s, t每个字符的大小,用cmp表示,如果当前字符不等,返回cmp即可;如果不越界的情况下比完了且都相等,再比较两个字符串的长度,返回两者之差即可
time: O(mn) -- m: length of String[] words, n: length of words, space: O(1)
class Solution { public boolean isAlienSorted(String[] words, String order) { int[] map = new int[26]; for(int i = 0; i < 26; i++) { map[order.charAt(i) - 'a'] = i; } for(int i = 1; i < words.length; i++) { if(compare(words[i - 1], words[i], map) > 0) return false; } return true; } // returns 1 if s1 > s2, -1 if s1 < s2, 0 if s1 == s2 private int compare(String s, String t, int[] map) { int m = s.length(), n = t.length(); for (int i = 0; i < m && i < n; i++) { int cmp = map[s.charAt(i) - 'a'] - map[t.charAt(i) - 'a']; if (cmp != 0) return cmp; } return m - n; } }