@@ -7,31 +7,34 @@ class DecodeString {
7
7
// Stack
8
8
// O(n) time, O(n) space
9
9
public String decodeString (String s ) {
10
- Stack <Integer > repeatCounts = new Stack <>();
11
- Stack <String > storedStrings = new Stack <>();
12
- storedStrings .push ("" );
13
-
14
- int i = 0 ;
15
- while (i < s .length ()) {
16
- char ch = s .charAt (i );
17
- if (Character .isDigit (ch )) {
18
- int start = i ;
19
- while (Character .isDigit (s .charAt (i + 1 ))) {
20
- i ++;
10
+ int num = 0 ;
11
+ Stack <String > stack = new Stack <>();
12
+ for (int i = 0 ; i < s .length (); i ++) {
13
+ char c = s .charAt (i );
14
+ if (Character .isDigit (c )) {
15
+ num = num * 10 + (c - '0' );
16
+ } else if (c == '[' ) {
17
+ stack .push (String .valueOf (num ));
18
+ stack .push ("[" );
19
+ num = 0 ;
20
+ } else if (c == ']' ) {
21
+ String substring = "" ;
22
+ while (!stack .empty () && !"[" .equals (stack .peek ())) {
23
+ substring = stack .pop () + substring ;
21
24
}
22
- repeatCounts .push (Integer .parseInt (s .substring (start , i + 1 )));
23
- } else if (ch == '[' ) {
24
- storedStrings .push ("" );
25
- } else if (ch == ']' ) {
26
- String repeatStr = storedStrings .pop ();
27
- int repeatCount = repeatCounts .pop ();
28
- storedStrings .push (storedStrings .pop () + repeatStr .repeat (repeatCount ));
25
+ stack .pop (); // pop '['
26
+ int repeatCount = Integer .parseInt (stack .pop ());
27
+ String repeatedSubstring = substring .repeat (repeatCount );
28
+ stack .add (repeatedSubstring );
29
29
} else {
30
- storedStrings .push (storedStrings . pop () + ch );
30
+ stack .push (String . valueOf ( c ) );
31
31
}
32
- i ++;
33
32
}
34
- return storedStrings .pop ();
33
+ String result = "" ;
34
+ while (!stack .empty ()) {
35
+ result = stack .pop () + result ;
36
+ }
37
+ return result ;
35
38
}
36
39
37
40
// Test
0 commit comments