https://leetcode.com/problems/decode-string/description/
Notes
- strings within strings would also need to be decoded
- the function that generates the string could be recursive since each sub-problem resembles the original problem
- number will be positive int
- no spaces
- matching brackets guaranteed
Examples
1
2
3
4Input:
"abcd10[a6[zd]]"
"14[w]100[dfg9[ik]]"
It’s really important to try several types of examples out before we jump into the final solution. One important point to note is that we need to keep passing in pos
as a reference it needs to be shared across all function invocations since we are moving through the string in one pass and need to keep track of the number of characters consumed. The solution below is a step in the right direction but has some flaws as noted below.
First Try
1 | class Solution { |
Issues
decodeString()
doesn’t need that ugly logic. We can just callparse()
.if (s[pos++] == ']'
is incorrect here since it will increment position and then check the value, which is hardly what we want.
Accepted Solution
1 | class Solution { |