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 a, string b, map<int, int> &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> &words, string order){map<int, int> mp;for (int i = 0; i < order.size(); i++){mp[order[i] - 'a'] = i;}for (int i = 0; i < words.size() - 1; i++){if (compareAlien(words[i], words[i + 1], mp) == -1){return false;}}return true;}int main(){vector<string> words = {"hello", "leetcode"};string order = "hlabcdefgijkmnopqrstuvwxyz";if (isAlienSorted(words, order))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment