Categories:

Tags:



Problem

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 lexicographically in this alien language.

Constraints

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

Solution

The problem Verifying an Alien Dictionary can be solved by creating a hash map for alphabet to order conversion and then comparing given strings lexicographically.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    bool isAlienSorted(vector<string> &words, string order)
    {
        unordered_map<char, char> hashmap;
        for (int i = 0; i < 26; i++)
            hashmap[order[i]] = i + 1;

        for (int i = 0; i < words.size() - 1; i++)
            for (int j = 0; j < words[i].length(); j++)
            {
                if (!(j < words[i + 1].length()))
                    return false;
                else if (hashmap[words[i][j]] < hashmap[words[i + 1][j]])
                    break;
                else if (hashmap[words[i][j]] > hashmap[words[i + 1][j]])
                    return false;
            }

        return true;
    }
};