File tree 1 file changed +54
-0
lines changed
scripts/algorithms/L/Lexicographical Numbers
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 94 ms (Top 5.29%) | Memory: 74.9 MB (Top 5.05%)
2
+ class Solution {
3
+
4
+ private final TrieNode trie = new TrieNode (' ' );
5
+
6
+ class TrieNode {
7
+
8
+ private Character digit ;
9
+ private String value ;
10
+ private boolean isWord ;
11
+ private Map <Character , TrieNode > children ;
12
+
13
+ TrieNode (Character c ){
14
+ this .digit = c ;
15
+ this .isWord = false ;
16
+ this .children = new HashMap <>();
17
+ }
18
+
19
+ void insert (String s ){
20
+ TrieNode current = this ;
21
+ for (Character c : s .toCharArray ()){
22
+ current = current .children .computeIfAbsent (c , k -> new TrieNode (c ));
23
+ }
24
+ current .value = s ;
25
+ current .isWord = true ;
26
+ }
27
+
28
+ List <Integer > getWordsPreOrder (){
29
+ return getWordsPreOrder (this );
30
+ }
31
+
32
+ private List <Integer > getWordsPreOrder (TrieNode root ){
33
+ List <Integer > result = new ArrayList <>();
34
+ if (root == null ){
35
+ return result ;
36
+ }
37
+
38
+ if (root .isWord ){
39
+ result .add (Integer .parseInt (root .value ));
40
+ }
41
+ for (TrieNode node : root .children .values ()){
42
+ result .addAll (getWordsPreOrder (node ));
43
+ }
44
+ return result ;
45
+ }
46
+ }
47
+
48
+ public List <Integer > lexicalOrder (int n ) {
49
+ for (int i = 1 ; i <=n ;i ++){
50
+ trie .insert (String .valueOf (i ));
51
+ }
52
+ return trie .getWordsPreOrder ();
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments