/**
* 自己的代码
* 用map存下order字符串中每个字符和下标的对应关系,方便后面判断两个字符的先后
* 其实没必要,直接用order.indexOf()来找所需字符的下标判断先后即可
* Runtime: 1 ms, faster than 53.19%
* Memory Usage: 39.1 MB, less than 24.42%
*/
class Solution {
public boolean isAlienSorted(String[] words, String order) {
HashMap<Character, Integer> dictionary = new HashMap();
char[] orderArr = order.toCharArray();
for (int i = 0; i < orderArr.length; i++) { // use map to store the character sequence in "order"
dictionary.put(orderArr[i], i);
}
for (int i = 1; i < words.length; i++) {
int maxIdx = Math.min(words[i - 1].length(), words[i].length());
int j = 0;
while (j < maxIdx && words[i - 1].charAt(j) == words[i].charAt(j)) { // find the first different character between words[i - 1] and words[i]
j++;
}
if (j == maxIdx) { // the shorter (or both) word is the prefix of the longer word
if (words[i - 1].length() > words[i].length()) { // the longer word should rank higher
return false;
}
} else if (dictionary.get(words[i - 1].charAt(j)) > dictionary.get(words[i].charAt(j))) { // if the sequence is wrong on the first character that differs in the adjacent words
return false;
}
}
return true;
}
}
/**
* 不用map保存order中的字符顺序,每次要找字符位置时直接用order.indexOf()
* 且合并了一些判断,简化了后面的代码
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 39 MB, less than 34.94%
*/
class Solution {
public boolean isAlienSorted(String[] words, String order) {
for (int i = 1; i < words.length; i++) {
int maxIdx = Math.min(words[i - 1].length(), words[i].length());
int toCompare = 0;
while (toCompare < maxIdx && words[i - 1].charAt(toCompare) == words[i].charAt(toCompare)) {
toCompare++;
}
if (toCompare == maxIdx && words[i - 1].length() > words[i].length() || toCompare != maxIdx && order.indexOf(words[i - 1].charAt(toCompare)) > order.indexOf(words[i].charAt(toCompare))) {
return false;
}
}
return true;
}
}
/**
* 一旦找到相邻两个word中第一个不相同的字符,就直接在循环中处理然后break
* 这样可以少一次word[i].charAt()的操作,提高算法效率
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 38.6 MB, less than 79.93%
*/
class Solution {
public boolean isAlienSorted(String[] words, String order) {
for (int i = 1; i < words.length; i++) {
int maxIdx = Math.min(words[i - 1].length(), words[i].length());
int toCompare = 0;
while (toCompare < maxIdx) {
char c1 = words[i - 1].charAt(toCompare), c2 = words[i].charAt(toCompare);
if (c1 != c2) {
if (order.indexOf(c1) > order.indexOf(c2)) {
return false;
}
break;
}
toCompare++;
}
if (toCompare == maxIdx && words[i - 1].length() > words[i].length()) {
return false;
}
}
return true;
}
}