953 验证外星语词典
某种外星语也使用英文小写字母,但可能顺序 order
不同。字母表的顺序(order
)是一些小写字母的排列。
给定一组用外星语书写的单词 words
,以及其字母表的顺序 order
,只有当给定的单词在这种外星语中按字典序排列时,返回 true
;否则,返回 false
。
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
//map存储每个字母所对应的次序
unordered_map<char,int>map;
//遍历字母表,并赋值
for(auto i=0;i<order.size();i++){
map[order[i]]=i;
}
//遍历单词
for(auto it=0;it<words.size()-1;it++){
//当前单词
string word1=words[it];
//当前单词的下一个单词
string word2=words[it+1];
//长度为二者中短的
int len=min(word1.size(),word2.size());
//初始化为false,标记是否确定word1小于word2
bool isvalid=false;
//比较当前单词与下一单词
for(auto j=0;j<len;j++){
//如果word1对应次序小于word2次序,则设置isvalid为true,并跳出循环
if(map[word1[j]]<map[word2[j]]){
isvalid=true;
break;
//若word1次序大于word2次序,返回false
}else if(map[word1[j]]>map[word2[j]]){
return false;
}
}
//如果比较的所有字符都相同,但word1比word2长,返回false
if(!isvalid &&word1.length()>word2.length()){
return false;
}
}
//如果都满足,返回true
return true;
}
};