给定字符串order表示字符先后顺序,问一组词是否按照order定义的顺序排序。是Alien Dict那道题反过来,思路类似,依次检查相邻的两个word找出第一个不同的字符,然后看是否符合order定义。为了方便查找字符的顺序,用一个map存字符和它的ranking。当没有字符不同时,再检测是否满足长度长的排后面。
/*
* @lc app=leetcode id=953 lang=cpp
*
* [953] Verifying an Alien Dictionary
*/
// @lc code=start
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
unordered_map<char, int> o;
for (int i = 0; i < order.length(); ++i) {
o[order[i]] = i;
}
for (int i = 1; i < words.size(); ++i) {
const auto s = words[i - 1], t = words[i];
bool found = false;
for (int j = 0; j < min(s.length(), t.length()); ++j) {
if (s[j] != t[j]) {
if (o[s[j]] > o[t[j]]) return false;
found = true;
break;
}
}
if (!found && s.length() > t.length()) return false;
}
return true;
}
};
// @lc code=end