Leetcode 953. Verifying an Alien Dictionary Java solution


class Solution {
    public boolean isAlienSorted(String[] words, String order) {
        int n = words.length;
        Map<Character, Integer> orderMap = new HashMap<>();
        for (int i = 0; i < order.length(); i++) {
            orderMap.put(order.charAt(i),i);
        }
        for (int i = 0; i < n - 1; i++) {
            if (!isSorted(words[i], words[i + 1], orderMap)) {
                return false;
            }
        }
        return true;
    }
    boolean isSorted(String first, String two, Map<Character, Integer> map) {
        int len1 = first.length();
        int len2 = two.length();
        int i = 0, j = 0;
        while (i < len1 && j < len2) {
            int o1 = map.get(first.charAt(i));
            int o2 = map.get(two.charAt(j));
            if ( o1 < o2) {
                return true;
            } else if (o1 == o2) {
                i++;
                j++;
            } else {
                return false;
            }
        }
        return i == len1;
    }
}

Comments

Popular posts from this blog

Can I name a method with the same name of the class in Java?

What is new in Java 8

Quicksort Java implementation