题目描述:
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 lexicographicaly in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
Note:
1 <= words.length <= 1001 <= words[i].length <= 20order.length == 26- All characters in
words[i]andorderare english lowercase letters.
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
unordered_map<char,int> hash;
for(int i=0;i<26;i++) hash[order[i]]=i;
for(int i=1;i<words.size();i++)
{
string s1=words[i-1];
string s2=words[i];
int j=0;
while(j<min(s1.size(),s2.size()))
{
if(hash[s1[j]]>hash[s2[j]]) return false;
else if(hash[s1[j]]<hash[s2[j]]) break;
j++;
}
if(j==s2.size()&&j<s1.size()) return false;
}
return true;
}
};
本文介绍了一种算法,用于判断一组用外星语言书写且遵循特定字母顺序的单词是否按字典序排列。通过将外星字母映射到地球上的英文字母并比较单词序列,该算法能够有效验证其排序正确性。

649

被折叠的 条评论
为什么被折叠?



