Leetcode.com problem 953: "Verifying an Alien Dictionary"

James S. Plank

Thu Feb 2 16:45:50 EST 2023

In Case Leetcode's Servers are Down

You are to implement the following class/method:

class Solution {
public:
    bool isAlienSorted(vector<string>& words, string order);
};


Examples

Personally, I think their examples aren't the best. Let me give you a different one:

Hints

This is a problem where a really good strategy is to convert each word in words its equivalent word when the normal order of the alphabet is used, and then simply use string comparison to determine the result.

Let's take that last example as an example. Since 'z' is the first character in order, we can convert any 'z' in words to an 'a', which is the first character in the normal order of the alphabet. Similarly, we'll convert 'y' to 'b', 'x' to 'c' and 'w' to 'd'. When we do that, words becomes "abc" and "abd", and we can use string comparison to verify that they are in the correct order.

To perform this conversion, I use a string called trans, where trans[i] is equal to the character to which I convert character 'a'+i. Let's use example 2 above. Here's what I want the translation to be:

worldabcefghijkmnpqstuvxyz
abcdefghijklmnopqrstuvwxyz

In other words, we'll convert 'w' to 'a', 'o' to 'b', etc. Accordingly, here is trans -- I put an alphabet on top so you can see what letters each character corresponds to:

         abcdefghijklmnopqrstuvwxyz
trans = "fhgeijklmnodpqbrsctuvwaxyz"

To convert a word using trans, we replace each letter with the letter it corresponds to in trans. For example, "word" is converted to "abce", and "word" is "abcde". Now, we can see that "word" is greater than "world", because "abce" is greater than "abcde."


Solution

Here's a solution (in Solution.cpp):

bool Solution::isAlienSorted(vector<string>& words, string order)
{
  string trans;
  int i, j;

  /* Create trans.  Trans[i-'a'] contains the character that character i
     should translate to (such as 'w' to 'a' in Example 4). */

  trans.resize(26, ' ');
  for (i = 0; i < order.size(); i++) trans[order[i]-'a'] = 'a' + i;

  /* Go through the words vector, and convert each word. */

  for (i = 0; i < words.size(); i++) {
    for (j = 0; j < words[i].size(); j++) {
      words[i][j] = trans[words[i][j]-'a'];
    }
    /* Compare each word to the one that precedes it, and if it is
       smaller, then the words are not in order -- return false. */

    if (i > 0 && words[i] < words[i-1]) return false;
  }

  /* If you get here without any words out of order, return true. */

  return true;
}

Verify that it works on the examples:

UNIX> echo hello leetcode hlabcdefgijkmnopqrstuvwxyz | ./a.out
True
UNIX> echo word world row worldabcefghijkmnpqstuvxyz | ./a.out
False
UNIX> echo apple app abcdefghijklmnopqrstuvwxyz | ./a.out
False
UNIX> echo zyx zyw zyxwvutsrqponmlkjihgfedcba | ./a.out
True
UNIX>