Skip to content

Commit e2e8f68

Browse files
update 953
1 parent 51897be commit e2e8f68

File tree

1 file changed

+18
-22
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-22
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_953.java

+18-22
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.fishercoder.solutions;
22

33
import java.util.Arrays;
4-
import java.util.Comparator;
54
import java.util.HashMap;
65
import java.util.Map;
76

@@ -29,39 +28,36 @@ public boolean isAlienSorted(String[] words, String order) {
2928

3029
private boolean sorted(String firstWord, String secondWord, Map<Character, Integer> map) {
3130
for (int i = 0; i < Math.min(firstWord.length(), secondWord.length()); i++) {
32-
if (firstWord.charAt(i) == secondWord.charAt(i)) {
33-
continue;
34-
} else {
35-
if (map.get(firstWord.charAt(i)) > map.get(secondWord.charAt(i))) {
36-
return false;
37-
} else {
38-
return true;
39-
}
31+
if (firstWord.charAt(i) != secondWord.charAt(i)) {
32+
return map.get(firstWord.charAt(i)) <= map.get(secondWord.charAt(i));
4033
}
4134
}
4235
return firstWord.length() <= secondWord.length();
4336
}
4437
}
4538

4639
public static class Solution2 {
40+
/**
41+
* Solution1 above is actually consistently faster than this Solution2 on LeetCode.
42+
*/
4743
public boolean isAlienSorted(String[] words, String order) {
4844
String[] copy = Arrays.copyOf(words, words.length);
49-
Arrays.sort(words, new Comparator<String>() {
50-
@Override
51-
public int compare(String o1, String o2) {
52-
int pos1 = 0;
53-
int pos2 = 0;
54-
for (int i = 0; i < Math.min(o1.length(), o2.length()) && pos1 == pos2; i++) {
55-
pos1 = order.indexOf(o1.charAt(i));
56-
pos2 = order.indexOf(o2.charAt(i));
57-
}
58-
59-
if (pos1 == pos2 && o1.length() != o2.length()) {
60-
return o1.length() - o2.length();
45+
Arrays.sort(words, (o1, o2) -> {
46+
int pos1 = 0;
47+
int pos2 = 0;
48+
for (int i = 0; i < Math.min(o1.length(), o2.length()); i++) {
49+
pos1 = order.indexOf(o1.charAt(i));
50+
pos2 = order.indexOf(o2.charAt(i));
51+
if (pos1 != pos2) {
52+
break;
6153
}
54+
}
6255

63-
return pos1 - pos2;
56+
if (pos1 == pos2 && o1.length() != o2.length()) {
57+
return o1.length() - o2.length();
6458
}
59+
60+
return pos1 - pos2;
6561
});
6662
for (int i = 0; i < words.length; i++) {
6763
if (!copy[i].equals(words[i])) {

0 commit comments

Comments
 (0)