Skip to content

Commit 75aa6cf

Browse files
author
Joseph Luce
authored
Update Decompressor.md
1 parent da7627a commit 75aa6cf

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

real_interview_questions/Google/Decompressor.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,21 @@ Eg. : a3[b2[c1[d]]]e will be decompressed as abcdcdbcdcdbcdcde.
55

66
Assume the string is well formed and number will always be followed by a [].
77

8+
# EXPLAINATION
9+
Yes, this question can get very complicated. Notice that 'a' is in the front of 'bcdcdbcdcdbcdcd' which corresponds to '[b2[c1[d]]]'. Then 'e' is at the end. You can think of 'a' and 'e' as a start of a new set of decompression/calculations.
10+
11+
The idea is to use recursion to decompress the string. My solution does it iteratively instead.
12+
13+
First break up the string into tokens, 'a3[b2[c1[d]]]e' -> 'a3','[','b2','[','c','[','d',']',']',']','e'
14+
15+
We will use two stacks, one stack(result stack) stores results of the decompressed string, which will be joined at the end.
16+
And another stack(token stack) keeps track of what tokens need to be decompressed.
17+
When encountering an open bracket, push the next token into the token stack.
18+
If we encounter a closed bracket, we should grab the top token then duplicate what was on the top result stack X times then append that token to the front and save it into the result stack.
19+
If we instead encounter a token, the suggests that a new result needs to be calculated, this is what was observed with 'a' and 'e' from above. That means any tokens remaining need to be calculated and saved into the result stack before we can start anew. A small trick is to place an empty string into the result stack as a placeholder for calculating the next set of decompression.
20+
821
# SOLUTION
9-
Need to clarify what a2[b2[c]d2[e]]f would decompress to. I would assume to 'abccdeebccdeef'.
22+
Need to clarify what 'a2[b2[c]d2[e]]f' would decompress to. I would assume to 'abccdeebccdeef'.
1023
```
1124
import re
1225

0 commit comments

Comments
 (0)