Skip to content

Latest commit

 

History

History
105 lines (83 loc) · 3.84 KB

File metadata and controls

105 lines (83 loc) · 3.84 KB

中文文档

Description

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

 

Example 1:

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).

 

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • order.length == 26
  • All characters in words[i] and order are English lowercase letters.

Solutions

Python3

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        index = {v: k for k, v in enumerate(order)}
        for i in range(len(words) - 1):
            word1, word2 = words[i], words[i + 1]
            len1, len2 = len(word1), len(word2)
            flag = True
            for j in range(min(len1, len2)):
                diff = index[word1[j]] - index[word2[j]]
                if diff > 0:
                    return False
                if diff < 0:
                    flag = False
                    break
            if flag and len1 > len2:
                return False
        return True

Java

class Solution {
    public boolean isAlienSorted(String[] words, String order) {
        int[] index = new int[26];
        for (int i = 0; i < 26; ++i) {
            index[order.charAt(i) - 'a'] = i;
        }
        for (int i = 0, m = words.length; i < m - 1; ++i) {
            String word1 = words[i];
            String word2 = words[i + 1];
            int len1 = word1.length();
            int len2 = word2.length();
            boolean flag = true;
            for (int j = 0, n = Math.min(len1, len2); j < n && flag; ++j) {
                int diff = index[word1.charAt(j) - 'a'] - index[word2.charAt(j) - 'a'];
                if (diff > 0) return false;
                if (diff < 0) flag = false;
            }
            if (flag && len1 > len2) return false;
        }
        return true;
    }
}

...