@@ -190,6 +190,12 @@ class AutocompleteSystem2 {
190190 private Node root ;
191191 private Node currNode ;
192192
193+ Comparator <String > comp = (s1 , s2 ) -> {
194+ int freqDiff = Integer .compare (this .freq .get (s1 ), this .freq .get (s2 ));
195+ if (freqDiff != 0 ) return freqDiff ;
196+ return -s1 .compareTo (s2 );
197+ };
198+
193199 public AutocompleteSystem2 (String [] sentences , int [] times ) {
194200 int N = sentences .length ;
195201 this .freq = new HashMap <>();
@@ -243,11 +249,7 @@ public List<String> input(char c) {
243249 }
244250 Node nn = next (this .currNode , c );
245251 this .currNode = nn ;
246- PriorityQueue <String > pq = new PriorityQueue <>(3 , (s1 , s2 ) -> {
247- int freqDiff = Integer .compare (this .freq .get (s1 ), this .freq .get (s2 ));
248- if (freqDiff != 0 ) return freqDiff ;
249- return -asciiOrder (s1 , s2 );
250- });
252+ PriorityQueue <String > pq = new PriorityQueue <>(3 , comp );
251253 if (nn != null ) {
252254 this .currNode = nn .eq ;
253255 if (nn .sent != null ) {
@@ -286,22 +288,6 @@ private void getAllSents(Node n, PriorityQueue<String> pq) {
286288 getAllSents (n .right , pq );
287289 }
288290
289- private int asciiOrder (String s1 , String s2 ) {
290- int i = 0 ;
291- int len1 = s1 .length ();
292- int len2 = s2 .length ();
293- char [] chars1 = s1 .toCharArray ();
294- char [] chars2 = s2 .toCharArray ();
295- while (i < len1 && i < len2 ) {
296- if (chars1 [i ] == chars2 [i ]) {
297- i ++;
298- continue ;
299- }
300- return Integer .compare (chars1 [i ], chars2 [i ]);
301- }
302- return Integer .compare (len1 , len2 );
303- }
304-
305291 class Node {
306292 char ch ;
307293 Node left ;
0 commit comments