Sponsored
Sponsored
This approach involves converting each character in the alien order to an index, which can be used to easily compare words. The idea is to take the given order of the language and map each character to its position in the order. Then, we can compare words by comparing their mapped indices.
Time Complexity: O(N)
, where N
is the total number of characters in all words. Space Complexity: O(1)
.
1#include <string>
2#include <vector>
3using namespace std;
4
5bool isAlienSorted(vector<string>& words, string order) {
6 vector<int> orderIdx(26);
7 for (int i = 0; i < order.size(); ++i) {
8 orderIdx[order[i] - 'a'] = i;
9 }
10
11 for (int i = 0; i < words.size() - 1; ++i) {
12 const string& w1 = words[i];
13 const string& w2 = words[i + 1];
14 size_t j = 0;
15 while (j < w1.length() && j < w2.length() && w1[j] == w2[j]) {
16 ++j;
17 }
18 if (j < w2.length() && (j >= w1.length() || orderIdx[w1[j] - 'a'] <= orderIdx[w2[j] - 'a'])) continue;
19 if (j == w2.length() || orderIdx[w1[j] - 'a'] > orderIdx[w2[j] - 'a']) return false;
20 }
21 return true;
22}
In C++, we achieve a similar outcome by using a vector
to store the order mappings. We iterate through each word pair and compare based on the mapped indices. If a lexicographic order mismatch is detected, we return false.
This approach employs a custom comparator to sort the words based on the alien order. We first map the order and then define a comparator that sorts based on this map. We check if the sorted version of the words matches the original order, indicating that they were sorted correctly in the alien dictionary.
Time Complexity: O(N log N)
due to sorting. Space Complexity: O(1)
.
1using System.Collections.Generic;
public class Solution {
public bool IsAlienSorted(string[] words, string order) {
int[] index = new int[26];
for (int i = 0; i < order.Length; i++) {
index[order[i] - 'a'] = i;
}
List<string> sortedWords = new List<string>(words);
sortedWords.Sort((w1, w2) => {
int minLength = Math.Min(w1.Length, w2.Length);
for (int i = 0; i < minLength; i++) {
if (w1[i] != w2[i]) {
return index[w1[i] - 'a'] - index[w2[i] - 'a'];
}
}
return w1.Length - w2.Length;
});
for (int i = 0; i < words.Length; i++) {
if (!words[i].Equals(sortedWords[i])) return false;
}
return true;
}
}
In C#, we use a custom Sort method to organize words based on mapped alien indices and then verify that the sorted list matches the input list.