Thursday, July 27, 2017

[leetcode] 269. Alien Dictionary

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:
  1. You may assume all letters are in lowercase.
  2. If the order is invalid, return an empty string.
  3. There may be multiple valid order of letters, return any one of them is fine.



Topological sorting:

1. Build the AOV
 using above fig. as example:
  unordered_map <char, int> m1;
m1[v1]=0;
m1[v2]=2;
m1[v3]=1;
...v4..=2;
...v5..=3;
....v6.=0;

  unordered_mpp <char, multisets<char>> m2;
m2[v1]={v2, v3, v4};
m2[v2]={}
......v3..={v2,v5}
.....v4...={v5}
......v6...={v4,v5}


2. extract the value inside 


  1. class Solution {  
  2. public:  
  3.     string alienOrder(vector<string>& words) {  
  4.         if(words.size()==0) return "";  
  5.         unordered_map<char, int> indegree;  
  6.         unordered_map<char, multiset<char>> hash;  
  7.         for(auto word: words)  
  8.             for(auto ch: word) indegree[ch] = 0;  
  9.         for(int i = 1; i < words.size(); i++)  
  10.         {  
  11.             int k =0len1 = words[i-1].size(), len2 = words[i].size();  
  12.             while(words[i-1][k] == words[i][k]) k++;  
  13.             if(k >= min(len1, len2)) continue;  
  14.             indegree[words[i][k]]++;  
  15.             hash[words[i-1][k]].insert(words[i][k]);  
  16.         }  
  17.         string ans;  
  18.         for(int i = 0; i< indegree.size(); i++)  
  19.         {  
  20.             char ch = ' ';  
  21.             for(auto val: indegree) if(!val.second) { ch = val.first; break; }  
  22.             if(ch == ' ') return "";  
  23.             ans += ch, indegree[ch]--;  
  24.             for(auto val: hash[ch]) indegree[val]--;  
  25.         }  
  26.         return ans;  
  27.     }  
  28. };  




















No comments:

Post a Comment