[LeetCode] Decode String

394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
string decode(string& s, int& pos) {
stringstream ss;
int repeat = 0;
for(; pos < s.length(); pos++) {
if('0' <= s[pos] && s[pos] <= '9') {
repeat = repeat * 10 + (s[pos] & 0b1111);
} else if(s[pos] == '[') {
string str = decode(s, ++pos);
while(repeat--) {ss << str;} repeat++;
} else if(s[pos] == ']') {
return ss.str();
} else {
ss << s[pos];
}
}
return ss.str();
}
public:
string decodeString(string s) {
int pos = 0;
return decode(s, pos);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/05/PS/LeetCode/decode-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.