-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAlien Dictionary.java
More file actions
88 lines (85 loc) · 1.72 KB
/
Alien Dictionary.java
File metadata and controls
88 lines (85 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//Source
//https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Stack;
class Alien_Dictionary
{
int v;
LinkedList<Integer> adj[];
Stack<Integer> st=new Stack<>();
Alien_Dictionary(int v)
{
this.v=v;
adj=new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int src,int dest)
{
adj[src].add(dest);
}
void topoSortUtil(int i,boolean visited[])
{
visited[i]=true;
for(int j:adj[i])
{
if(!visited[j])
topoSortUtil(j,visited);
}
st.push(i);
}
void topoSort()
{
boolean visited[]=new boolean[v];
for(int i=0;i<v;i++)
{
if(!visited[i])
topoSortUtil(i,visited);
}
while(!st.isEmpty())
{
System.out.print((char)(st.pop()+(int)'a')+" ");
}
}
static void printOrder(String dict[],int v)
{
Alien_Dictionary g=new Alien_Dictionary(v);
for(int i=0;i<dict.length-1;i++)
{
String word1=dict[i];
String word2=dict[i+1];
for(int j=0;j<Math.min(word1.length(),word2.length());j++)
{
if(word1.charAt(j)!=word2.charAt(j))
{
g.addEdge((int)word1.charAt(j)-'a',(int)word2.charAt(j)-'a');
break;
}
}
}
g.topoSort();
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=(int)'a';
String []a=new String[n];
for(int i=0;i<n;i++)
{
a[i]=sc.next();
}
for(int i=0;i<n;i++)
{
for(int j=0;j<a[i].length();j++)
{
if((int)a[i].charAt(j)>m)
m=(int)a[i].charAt(j);
}
}
m=m-96;
printOrder(a,m);
}
}