Go•verifying-an-alien-dictionary/solution.go
package main
func isAlienSorted(words []string, order string) bool {
rank := map[byte]int{}
for index := range order {
rank[order[index]] = index
}
for index := 1; index < len(words); index++ {
left, right := words[index-1], words[index]
different := false
limit := len(left)
if len(right) < limit {
limit = len(right)
}
for position := 0; position < limit; position++ {
if left[position] != right[position] {
if rank[left[position]] > rank[right[position]] {
return false
}
different = true
break
}
}
if !different && len(left) > len(right) {
return false
}
}
return true
}
Python•verifying-an-alien-dictionary/solution.py
class Solution:
def isAlienSorted(self, words: list[str], order: str) -> bool:
rank = {letter: index for index, letter in enumerate(order)}
for left, right in zip(words, words[class="syntax-number">1:]):
for a, b in zip(left, right):
if a != b:
if rank[a] > rank[b]: return False
break
else:
if len(left) > len(right): return False
return True
TypeScript•verifying-an-alien-dictionary/solution.ts
function isAlienSorted(words: string[], order: string): boolean {
const rank = new Map([...order].map((letter, index) => [letter, index]));
for (let index = class="syntax-number">1; index < words.length; index += class="syntax-number">1) {
const left = words[index - class="syntax-number">1]; const right = words[index]; let different = false;
for (let position = class="syntax-number">0; position < Math.min(left.length, right.length); position += class="syntax-number">1) if (left[position] !== right[position]) { if (rank.get(left[position])! > rank.get(right[position])!) return false; different = true; break; }
if (!different && left.length > right.length) return false;
}
return true;
}