Source: https://leetcode.com/problems/verifying-an-alien-dictionary/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 lexicographically 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class Solution { public boolean isAlienSorted(String[] words, String order) { Map<Character, Integer> orderMap = new HashMap<>(); char[] arr = order.toCharArray(); for(int i=0;i<arr.length;i++){ orderMap.put(arr[i], i); } for(int i=1;i<words.length;i++){ if(!compare(orderMap, words[i-1], words[i])){ return false; } } return true; } private boolean compare(Map<Character, Integer> orderMap, String a, String b){ int i=0; int j=0; while(i<a.length() && j<b.length()){ //if a character in string a is smaller than a character in string b if(orderMap.get(a.charAt(i)) < orderMap.get(b.charAt(j))){ return true; } // if a character in string a is equals to a character in string b // then we have to check the next character in both the strings else if(orderMap.get(a.charAt(i)) == orderMap.get(b.charAt(j))) { i++; j++; } //otherwise return false else { return false; } } //check if the length of string a is smaller or equals to string b return a.length()<=b.length(); } } |