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 words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
[ "wrt", "wrf", "er", "ett", "rftt" ]
The correct order is: "wertf"
.
Note:
- You may assume all letters are in lowercase.
- If the order is invalid, return an empty string.
- There may be multiple valid order of letters, return any one of them is fine.
#include<iostream> #include<string> #include<vector> #include<set> #include<map> using namespace std; string getOrder(vector<string>& v) { int n = v.size(), i, j; if (n < 1) return ""; set<char> st; for (i = 0; i < n; i++) { for (j = 0; j < v[i].size(); j++) st.insert(v[i][j]); } map<char, set<char>> mp; for (set<char>::iterator it = st.begin(); it != st.end(); it++) mp[*it] = set<char>(); string ans = ""; for (i = 1; i < n; i++) { for (j = 0; j < v[i].size() && j < v[i - 1].size(); j++) { if (v[i][j] != v[i - 1][j]) { mp[v[i][j]].insert(v[i - 1][j]); break; } } } while (!mp.empty()) { int num = 0; for (map<char, set<char>>::iterator it = mp.begin(); it != mp.end(); ) { if ((it->second).empty()) { char c = it->first; ans += c; mp.erase(it++); num++; for (map<char, set<char>>::iterator iter = mp.begin(); iter != mp.end(); iter++) iter->second.erase(c); } else it++; } if (0 == num) return ""; } return ans; } int main() { vector<string> v; v.push_back("w"); v.push_back("t"); v.push_back("e"); v.push_back("r"); v.push_back("rf"); cout << getOrder(v) << endl; return 0; }
st:所有出现的字母的集合。
mp:每个字母有一个set,为在这个字母之前的字母的集合。
拓扑排序。