题目描述
给定一个字符串数组和字典排序,这个字典序即外星人的字母顺序表,验证字符串数组是不是按照升序排列。
题解
写一个比较函数,然后两两验证。
class Solution {
public:
// check if a is less than b
bool check (string a, string b, unordered_map<char, int> &mp) {
int size1 = a.length(), size2 = b.length();
for (int i = 0; i < min(size1, size2); i++) {
if (mp[a[i]] < mp[b[i]]) { // a is less than b
return true;
} else if (mp[a[i]] > mp[b[i]]) {
return false;
}
}
if (size1 < size2) {
return true;
}
return false;
}
bool isAlienSorted(vector<string>& words, string order) {
if (words.size() < 2) {
return true;
}
// 给定一个字符顺序,判断出现的单词是否按照升序排列
unordered_map<char, int> mp;
for (int i = 0; i < order.length(); i++) {
mp[order[i]] = i;
}
// cout << true << check("hello", "helloo", mp) << endl;
// 两两比较
for (int i = 1; i < words.size(); i++) {
if (!(check(words[i - 1], words[i], mp))) {
return false;
}
}
return true;
}
};
需要注意的是,check
函数,从左到右,如果有一个比对方大或者小,直接返回结果,不返回表示都一样,再判定长度即可,谁长谁大。
END.