-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
540fd06
commit 9804f51
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
class Solution{ | ||
private: | ||
vector<int>topoSort(int V,vector<int>adj[]){ | ||
int indegree[V]={0}; | ||
for(int i=0;i<V;i++){ | ||
for(auto it:adj[i]){ | ||
indegree[it]++; | ||
} | ||
} | ||
queue<int>q; | ||
for(int i=0;i<V;i++){ | ||
if(indegree[i]==0){ | ||
q.push(i); | ||
} | ||
|
||
}vector<int>topo; | ||
while(!q.empty()){ | ||
int node=q.front(); | ||
q.pop(); | ||
topo.push_back(node); | ||
|
||
for(auto it:adj[node]){ | ||
indegree[it]--; | ||
if(indegree[it]==0){ | ||
q.push(it); | ||
} | ||
} | ||
} | ||
return topo; | ||
} | ||
public: | ||
string findOrder(string dict[], int N, int K) { | ||
//code here | ||
vector<int>adj[K]; | ||
for(int i=0;i<N-1;i++){ | ||
string s1=dict[i]; | ||
string s2=dict[i+1]; | ||
int len=min(s1.size(),s2.size()); | ||
for(int ptr=0;ptr<len;ptr++){ | ||
if(s1[ptr]!=s2[ptr]){ | ||
adj[s1[ptr]-'a'].push_back(s2[ptr]-'a'); | ||
break; | ||
} | ||
|
||
} | ||
} | ||
vector<int>topo=topoSort(K,adj); | ||
|
||
string ans=""; | ||
for(auto it:topo){ | ||
ans=ans+char(it+'a'); | ||
} | ||
return ans; | ||
} | ||
}; |