You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
/** * @param {string[]} words * @param {string} order * @return {boolean} */varisAlienSorted=function(words,order){letmap=newMap();for(leti=0;i<order.length;i++){//map stores all letters in 'orders' and its corresponding indexmap.set(order[i],i);}for(letj=1;j<words.length;j++){letprev=words[j-1];letcurr=words[j];//For example, ["hello","leetcode"], prev[0] = 'h', curr[0] = 'l', and l cannot come before hif(map.get(prev[0])>map.get(curr[0])){returnfalse;}elseif(prev[0]===curr[0]){letpointer=1;//We must check if pointer is out of index, otherwise for test case like prev: 'hello'//curr: 'hello', the while loop never stops.while(prev[pointer]===curr[pointer]&&pointer<Math.max(curr.length,prev.length)){pointer++;}/* if prev[pointer] is in orders (so at least is has 0 in map), but curr[pointer] is not in order, then return false. Works for ["apple","app"], since l and e is not in map Also, in the example words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz", we can see that the index of l is smaller than the index of d. But should be vice versa since d came before l, map.get(prev[pointer]) < map.get(curr[pointer] is correct. */if((map.get(prev[pointer])>=0&&!map.get(curr[pointer]))||map.get(prev[pointer])>map.get(curr[pointer])){returnfalse;}}}returntrue;};