File tree 1 file changed +20
-25
lines changed
scripts/algorithms/D/Decrypt String from Alphabet to Integer Mapping
1 file changed +20
-25
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 2 ms (Top 43.3%) | Memory: 40.72 MB (Top 56.6%)
2
+
1
3
class Solution {
2
- public String freqAlphabets (String s ) {
3
- Stack <Character > stk = new Stack <>();
4
- int i =0 ;
5
- String decoded ="" ;
6
- while (i <s .length ()) {
7
- if (s .charAt (i )=='#' ) { // if # is encountered, convert and store corresponding alphabet
8
- int c1 =stk .pop ()-48 ;
9
- int c2 =stk .pop ()-48 ;
10
- int c = 96 +(10 *c2 )+c1 ;
11
- stk .push ((char )c );
12
-
13
- } else {
14
- stk .push (s .charAt (i ));
15
- }
16
- i ++;
4
+ public String freqAlphabets (String str ) {
5
+ HashMap <String , Character > map = new HashMap <>();
6
+ int k = 1 ;
7
+ for (char ch = 'a' ; ch <= 'z' ; ch ++) {
8
+ if (ch < 'j' )
9
+ map .put (String .valueOf (k ++), ch );
10
+ else
11
+ map .put (String .valueOf (k ++)+"#" , ch );
17
12
}
18
13
19
- String temp ="" ;
20
-
21
- while (!stk .isEmpty ()) {
22
- char c =stk .pop ();
23
- if (c >='1' && c <='9' ) {
24
- int val =48 +c ;
25
- temp =(char )val +"" ;
14
+ StringBuilder sb = new StringBuilder ();
15
+ int i = str .length () - 1 ;
16
+ while (i >= 0 ) {
17
+ if (str .charAt (i ) == '#' ) {
18
+ sb .append (map .get (str .substring (i - 2 , i +1 )));
19
+ i -= 3 ;
26
20
} else {
27
- temp =c +"" ;
21
+ sb .append (map .get (str .substring (i , i + 1 )));
22
+ i --;
28
23
}
29
- decoded =temp +decoded ;
30
24
}
31
- return decoded ;
25
+
26
+ return sb .reverse ().toString ();
32
27
}
33
28
}
You can’t perform that action at this time.
0 commit comments