Advertisement
1988coder

953. Verifying an Alien Dictionary

Dec 14th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. /*
  2. Time Complexity: O(M * N) or O(Total number of chars in words array)
  3. Space Complexity: O(1) or O(26)
  4.  
  5. M = Average length of each word
  6. N = Number of words
  7. */
  8. class Solution {
  9.     public boolean isAlienSorted(String[] words, String order) throws IllegalArgumentException {
  10.         if (words == null || order == null || order.length() != 26) {
  11.             throw new IllegalArgumentException("Invalid input");
  12.         }
  13.         if (words.length < 2) {
  14.             return true;
  15.         }
  16.        
  17.         int[] orderDict = new int[26];
  18.         for (int i = 0; i < order.length(); i++) {
  19.             orderDict[order.charAt(i) - 'a'] = i;
  20.         }
  21.        
  22.         for (int i = 1; i < words.length; i++) {
  23.             if (compare(words[i-1], words[i], orderDict) > 0) {
  24.                 return false;
  25.             }
  26.         }
  27.        
  28.         return true;
  29.     }
  30.    
  31.     private int compare(String A, String B, int[] orderDict) {
  32.         int lenA = A.length();
  33.         int lenB = B.length();
  34.         for (int i = 0; i < Math.min(lenA, lenB); i++) {
  35.             if (A.charAt(i) != B.charAt(i)) {
  36.                 return orderDict[A.charAt(i)-'a'] - orderDict[B.charAt(i)-'a'];
  37.             }
  38.         }
  39.         return lenA - lenB;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement