Description:
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
Note:
You may assume all letters are in lowercase.
You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
Example:
Example 1:
Given the following words in dictionary,
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
The correct order is: "wertf".
Example 2:
Given the following words in dictionary,
[
"z",
"x"
]
The correct order is: "zx".
Example 3:
Given the following words in dictionary,
[
"z",
"x",
"z"
]
The order is invalid, so return "".
Link:
https://leetcode.com/problems/alien-dictionary/description/
解題方法:
這是一道圖求環的題。
第一步:
直接遍歷輸入數組,從每兩個相連的單詞查找已有的先后順序信息。
例如:abc, abd
可以得出:c > d
因為輸入的單詞是由詞典順序排序的,所以不會存在不相鄰的兩個單詞也有必要的順序信息。
將得到的信息存在哈希表里。
第二步:
對圖進行求環,這里我用的是DFS的方法,雖然BFS更快,但是這道題決定時間復雜度的在于遍歷單詞的每個字母。
在DFS的同時計算每個單詞依照語言順序后面有多少個字母。(用hash_set來統計)
如果圖中有環,說明有沖突,沒有一個有效的字母順序。
如果有字母存在相同的統計結果,我們只要輸出其中的一種。
第三步:
對以上統計結果(字母-->該字母依照語言順序后面有多少個字母)排序(降序),求出結果即為我們需要的結果。
Tips:
Time Complexity:
O(N) N為所有單詞所有字母的總和
完整代碼:
string alienOrder(vector<string>& words) {
int len = words.size();
if(!len)
return "";
if(len == 1)
return words[0];
//get rules between two characters (build Graph)
unordered_map<char, unordered_set<char>> characters;
for(int i = len - 1; i > 0; i--) {
string str2 = words[i];
string str1 = words[i - 1];
for(char cha: str1)
if(characters.find(cha) == characters.end())
characters[cha] = unordered_set<char>();
for(char cha: str2)
if(characters.find(cha) == characters.end())
characters[cha] = unordered_set<char>();
for(int i = 0; i < str1.size() && i < str2.size(); i++) {
if(str1[i] != str2[i]) {
characters[str1[i]].insert(str2[i]);
break;
}
}
}
//DFS
vector<pair<char, int>> order;
for(auto a: characters) {
bool valid = true;
unordered_set<char> visited;
unordered_set<char> count;
visited.insert(a.first);
dfs(a.first, characters, valid, visited, count);
order.push_back(pair<char, int>(a.first, count.size()));
if(!valid)
return "";
}
//sort
sort(order.begin(), order.end(), [](pair<char, int> a, pair<char, int> b){
return a.second > b.second;
});
//build result
string result = "";
for(auto a: order) {
result += a.first;
}
return result;
}
void dfs(char curr, unordered_map<char, unordered_set<char>>& characters, bool& valid, unordered_set<char>& visited, unordered_set<char>& count) {
count.insert(curr);
if(!valid || characters[curr].empty())
return;
for(auto a: characters[curr]) {
if(visited.find(a) != visited.end()) {
valid = false;
return;
}
visited.insert(a);
dfs(a, characters, valid, visited, count);
visited.erase(a);
}
}