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).
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
- All characters in
words[i]
andorder
are English lowercase letters.
class Solution { public boolean isAlienSorted(String[] words, String order) { int[] map = new int[26]; for(int i = 0; i < order.length(); i++) map[order.charAt(i) - 'a'] = i; for(int i = 0; i < words.length - 1; i++) { for(int j = 0; j < words[i].length(); j++) { if(j >= words[i + 1].length()) return false; if(words[i].charAt(j) != words[i + 1].charAt(j)) { int cur = words[i].charAt(j) - 'a'; int nex = words[i + 1].charAt(j) - 'a'; if(map[cur] > map[nex]) return false; else break; } } } return true; } }
一个一个往后比较,先用一个map记录外星文字的顺序,0-26代表a-z,value是外星文字顺序。
然后开始比较,如果当前word的长度已经大于下一个word长度,就直接return false:apple,app。
如果两个word的char相等就不比较,相等就只有两种情况:1. sorted,2. unsorted
把这两个char拿到,放在外星文字的map比较,如果cur 》 nex,说明unsorted,否则说明sorted,直接break。