Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Time Complexity: O(M * N) or O(Total number of chars in words array)
- Space Complexity: O(1) or O(26)
- M = Average length of each word
- N = Number of words
- */
- class Solution {
- public boolean isAlienSorted(String[] words, String order) throws IllegalArgumentException {
- if (words == null || order == null || order.length() != 26) {
- throw new IllegalArgumentException("Invalid input");
- }
- if (words.length < 2) {
- return true;
- }
- int[] orderDict = new int[26];
- for (int i = 0; i < order.length(); i++) {
- orderDict[order.charAt(i) - 'a'] = i;
- }
- for (int i = 1; i < words.length; i++) {
- if (compare(words[i-1], words[i], orderDict) > 0) {
- return false;
- }
- }
- return true;
- }
- private int compare(String A, String B, int[] orderDict) {
- int lenA = A.length();
- int lenB = B.length();
- for (int i = 0; i < Math.min(lenA, lenB); i++) {
- if (A.charAt(i) != B.charAt(i)) {
- return orderDict[A.charAt(i)-'a'] - orderDict[B.charAt(i)-'a'];
- }
- }
- return lenA - lenB;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement