Sanath12345

Untitled

Sep 23rd, 2021
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. class Solution{
  2. public:
  3. vector<int> adjlst[30];
  4. int vis[30];
  5. string ans="";
  6. stack<int> S;
  7. void toplogicalSort(int v){
  8. if(vis[v]==1) return ;
  9. vis[v]=1;
  10. for(auto i:adjlst[v]){
  11. toplogicalSort(i);
  12. }
  13. S.push(v);
  14. }
  15. string findOrder(string dict[], int N, int K) {
  16. for(int i=1;i<N;i++){
  17. int j=0;
  18. int z=min(dict[i-1].length(),dict[i].length());
  19. while(j<z and dict[i-1][j]==dict[i][j]) j++;
  20. if(j==z) continue;
  21. else{
  22. adjlst[dict[i-1][j]-'a'].push_back(dict[i][j]-'a');
  23. }
  24. }
  25. for(int i=0;i<26;i++){
  26. toplogicalSort(i);
  27. }
  28. while(!S.empty()){
  29. char c=S.top()+'a';
  30. ans+=c;
  31. S.pop();
  32. }
  33. return ans;
  34. }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment