@@ -14,24 +14,26 @@ public static class Solution1 {
14
14
* reference: https://discuss.leetcode.com/topic/28308/java-ac-solution-using-bfs
15
15
*/
16
16
public String alienOrder (String [] words ) {
17
- Map <Character , Set <Character >> map = new HashMap ();
17
+ Map <Character , Set <Character >> map = new HashMap <> ();
18
18
Map <Character , Integer > degree = new HashMap <>();
19
19
String result = "" ;
20
20
if (words == null || words .length == 0 ) {
21
21
return result ;
22
22
}
23
23
for (String s : words ) {
24
24
for (char c : s .toCharArray ()) {
25
- degree .put (c , 0 );//keeps overwriting it, the purpose is to create one entry
26
- //for each letter in the degree map
25
+ degree .put (c , 0 );
27
26
}
28
27
}
29
28
for (int i = 0 ; i < words .length - 1 ; i ++) {
30
- String cur = words [i ];
29
+ String curr = words [i ];
31
30
String next = words [i + 1 ];
32
- int length = Math .min (cur .length (), next .length ());
33
- for (int j = 0 ; j < length ; j ++) {
34
- char c1 = cur .charAt (j );
31
+ if (curr .length () > next .length () && curr .startsWith (next )) {
32
+ return "" ;
33
+ }
34
+ int minLen = Math .min (curr .length (), next .length ());
35
+ for (int j = 0 ; j < minLen ; j ++) {
36
+ char c1 = curr .charAt (j );
35
37
char c2 = next .charAt (j );
36
38
if (c1 != c2 ) {
37
39
Set <Character > set = new HashSet <>();
@@ -50,17 +52,17 @@ public String alienOrder(String[] words) {
50
52
Queue <Character > queue = new LinkedList <>();
51
53
for (char c : degree .keySet ()) {
52
54
if (degree .get (c ) == 0 ) {
53
- queue .add (c );
55
+ queue .offer (c );
54
56
}
55
57
}
56
58
while (!queue .isEmpty ()) {
57
- char c = queue .remove ();
58
- result += c ;
59
- if (map .containsKey (c )) {
60
- for (char c2 : map .get (c )) {
61
- degree .put (c2 , degree .get (c2 ) - 1 );
62
- if (degree .get (c2 ) == 0 ) {
63
- queue .add ( c2 );
59
+ char curr = queue .poll ();
60
+ result += curr ;
61
+ if (map .containsKey (curr )) {
62
+ for (char c : map .get (curr )) {
63
+ degree .put (c , degree .get (c ) - 1 );
64
+ if (degree .get (c ) == 0 ) {
65
+ queue .offer ( c );
64
66
}
65
67
}
66
68
}
0 commit comments