Decode String
https://leetcode.com/problems/decode-string/description/
Thoughts
Code
/*
* @lc app=leetcode id=394 lang=cpp
*
* [394] Decode String
*/
// @lc code=start
class Solution {
public:
string decodeString(string s) {
stack<string> st;
stack<int> counts;
int num = 0;
string res;
for (const auto c : s) {
if (c == '[') {
counts.push(num);
num = 0;
st.push(res);
res.clear();
} else if (c >= '0' && c <= '9') {
num *= 10;
num += c - '0';
} else if (c == ']') {
const auto count = counts.top();
auto t = st.empty() ? "" : st.top();
for (int i = 0; i < count; ++i) {
t += res;
}
if (!st.empty()) st.pop();
counts.pop();
res = t;
} else {
res += c;
}
}
return res;
}
};
// @lc code=end
Analysis
Last updated