Verifying an Alien Dictionary

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.

Example:

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

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int compareAlien(string astring bmap<intint&mp)
{
    int i = 0;
    while (i < a.length() && i < b.length())
    {
        if (mp[a[i] - 'a'] > mp[b[i] - 'a'])
            return -1;
        if (mp[a[i] - 'a'] < mp[b[i] - 'a'])
            return 1;
        i++;
    }
    if (i >= a.length())
        return 1;
    if (i >= b.length())
        return -1;
    return 0;
}

bool isAlienSorted(vector<string&wordsstring order)
{
    map<intintmp;

    for (int i = 0i < order.size(); i++)
    {
        mp[order[i] - 'a'] = i;
    }

    for (int i = 0i < words.size() - 1i++)
    {
        if (compareAlien(words[i]words[i + 1]mp) == -1)
        {
            return false;
        }
    }

    return true;
}

int main()
{
    vector<stringwords = {"hello""leetcode"};
    string order = "hlabcdefgijkmnopqrstuvwxyz";

    if (isAlienSorted(wordsorder))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment