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).
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
- All characters in
words[i]
andorder
are English lowercase letters.
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 | class Solution { public boolean isAlienSorted(String[] words, String order) { Map<Character, Integer> map = new HashMap<>(); for(int i=0; i<order.length(); ++i) map.put(order.charAt(i), i); int i = 0; boolean cont = true; while(cont){ cont = false; char ch0 = '.'; String pref0 = ""; for(String w : words){ int len = w.length(); if(i<len){ cont = true; String pref1 = w.substring(0, i); char ch1 = w.charAt(i); if(pref0.equals(pref1)){ if(ch0!='.' && ch0!=ch1){ //ch0 < ch if(map.get(ch0) > map.get(ch1)) return false; } } pref0 = pref1; ch0 = ch1; }else if(i==len){ String pref1 = w; char ch1 = '.'; if(pref0.equals(pref1) && ch0!='.') return false; pref0 = pref1; ch0 = ch1; } } i++; } return true; } } |
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 | class Solution { public boolean isAlienSorted(String[] words, String order) { Map<Character, Integer> map = new HashMap<>(); for(int i=0; i<order.length(); ++i){ char ch = order.charAt(i); map.put(ch, i); } for(int i=0; i<words.length-1; ++i){ if(!check(words[i], words[i+1], map)) return false; } return true; } boolean check(String w1, String w2, Map<Character, Integer> map){ int n1 = w1.length(), n2 = w2.length(); int i = 0; while(i<n1 && i<n2){ int p1 = map.get(w1.charAt(i)); int p2 = map.get(w2.charAt(i)); if(p1!=p2) return p1<p2; i++; } return n1<=n2; } } |
No comments:
Post a Comment