aero2146

Verifying an Alien Dictionary

Apr 10th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. class Solution(object):
  2.     def isAlienSorted(self, words, order):
  3.         order_index = {c: i for i, c in enumerate(order)}
  4.  
  5.         for i in xrange(len(words) - 1):
  6.             word1 = words[i]
  7.             word2 = words[i+1]
  8.  
  9.             # Find the first difference word1[k] != word2[k].
  10.             for k in xrange(min(len(word1), len(word2))):
  11.                 # If they compare badly, it's not sorted.
  12.                 if word1[k] != word2[k]:
  13.                     if order_index[word1[k]] > order_index[word2[k]]:
  14.                         return False
  15.                     break
  16.             else:
  17.                 # If we didn't find a first difference, the
  18.                 # words are like ("app", "apple").
  19.                 if len(word1) > len(word2):
  20.                     return False
  21.  
  22.         return True
Add Comment
Please, Sign In to add comment