|
1 | 1 | classSolution {
|
2 | 2 | publicbooleanisAlienSorted(String[]words,Stringorder) {
|
3 |
| -Map<Character,Integer>dictionary =newHashMap<>(); |
4 |
| -for (inti =0;i <order.length();i++) { |
5 |
| -dictionary.put(order.charAt(i),i); |
| 3 | +Map<Character,Integer>map =newHashMap<>(); |
| 4 | +intidx =0; |
| 5 | +for (charc :order.toCharArray()) { |
| 6 | +map.put(c,idx++); |
6 | 7 | }
|
7 |
| -for (inti =0;i <words.length -1;i++) { |
8 |
| -if (!hasCorrectOrder(words[i],words[i +1],dictionary)) { |
| 8 | +for (inti =1;i <words.length;i++) { |
| 9 | +if (!isSorted(words[i -1],words[i],map)) { |
9 | 10 | returnfalse;
|
10 | 11 | }
|
11 | 12 | }
|
12 | 13 | returntrue;
|
13 | 14 | }
|
14 | 15 |
|
15 |
| -privatebooleanhasCorrectOrder(StringfirstWord,StringsecondWord,Map<Character,Integer>dictionary) { |
16 |
| -intidxOne =0; |
17 |
| -intidxTwo =0; |
18 |
| -booleancorrectOrder =false; |
19 |
| -while (idxOne <firstWord.length() &&idxTwo <secondWord.length()) { |
20 |
| -intdictionaryDiff =dictionary.get(firstWord.charAt(idxOne++)) -dictionary.get(secondWord.charAt(idxTwo++)); |
21 |
| -if (dictionaryDiff >0) { |
| 16 | +privatebooleanisSorted(StringwordOne,StringwordTwo,Map<Character,Integer>map) { |
| 17 | +for (inti =0;i <Math.min(wordOne.length(),wordTwo.length());i++) { |
| 18 | +intdiff =map.get(wordOne.charAt(i)) -map.get(wordTwo.charAt(i)); |
| 19 | +if (diff >0) { |
22 | 20 | returnfalse;
|
23 |
| - } |
24 |
| -if (dictionaryDiff <0) { |
25 |
| -correctOrder =true; |
26 |
| -break; |
| 21 | + }elseif (diff <0) { |
| 22 | +returntrue; |
27 | 23 | }
|
28 | 24 | }
|
29 |
| -returncorrectOrder ||firstWord.length() <=secondWord.length(); |
| 25 | +returnwordOne.length() <=wordTwo.length(); |
30 | 26 | }
|
31 | 27 | }
|