Computer Science/C++
[C++] ostringstream, isdigit
focalpoint
2023. 8. 29. 00:48
LeetCode: 394. Decode String
https://leetcode.com/problems/decode-string/description/
Decode String - LeetCode
Can you solve this real interview question? 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 g
leetcode.com
class Solution {
public:
int idx = 0;
string s;
string decodeString(string s) {
this->s = s;
return helper();
}
string helper() {
ostringstream oss;
while (idx < s.size()) {
if (isdigit(s[idx])) {
int num = 0;
while (s[idx] != '[') {
num = num * 10 + s[idx] - '0';
idx++;
}
idx++;
string str = helper();
for (int t = 0; t < num; t++) {
oss << str;
}
}
else if (s[idx] == ']') {
idx++;
return oss.str();
}
else {
oss << s[idx];
idx++;
}
}
return oss.str();
}
};