解题思路:
(1)首先建立一个hash table保存26个英文字母出现的位置
(2)再依次比较相邻字符串的大小即可
class Solution {
public:
/**
* @param words: the array of string means the list of words
* @param order: a string indicate the order of letters
* @return: return true or false
*/
bool compare(const string &str1,const string &str2,int *a) {
// str1在str2的前面?
int i=0,j=0;
while(i<str1.length() && j<str2.length()) {
if(a[str1[i]-'a'] < a[str2[j]-'a']) return true;
else if(a[str1[i]-'a'] > a[str2[j]-'a']) return false;
else i++;j++;
}
if(i==str1.length() && j==str2.length()) return true;
else if(i==str1.length() && j!=str2.length()) return true;
else return false;
}
bool isAlienSorted(vector<string> &words, string &order) {
int index[26]={0};
for(int i=0;i<order.length();i++) index[order[i]-'a']=i;
for(int i=0;i+1<words.size();i++) {
if(!compare(words[i],words[i+1],index)) return false;
}
return true;
}
};
版权声明:本文为coolsunxu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。