class Solution {
public:
string decodeString(string s) {
int sIdx = 0;
stack<char> st;
while (sIdx < s.size()) {
if (s[sIdx] == ']') {
++sIdx; // skip ']'
string encodedStr;
while (!st.empty() && st.top() != '[') {
encodedStr.push_back(st.top());
st.pop();
}
st.pop(); // get rid of '['
int k = 0, x = 1;
while (!st.empty() && isdigit(st.top())) {
k = k + (st.top() - '0') * x;
x *= 10;
st.pop();
}
string decodedStr;
while(k > 0) {
decodedStr += encodedStr;
--k;
}
for (int i = decodedStr.size() - 1; i >= 0; --i) {
st.push(decodedStr[i]);
}
} else {
// s[sIdx] != ']' is true
st.push(s[sIdx++]);
}
}
string answer;
while (!st.empty()) {
answer = st.top() + answer;
st.pop();
}
return answer;
}
};
class Solution {
public:
string decodeString(string s) {
int i = 0;
return decodeString(s, i);
}
private:
string decodeString(string s, int &i) {
string decoded;
while (i < s.size() && s[i] != ']') {
if (isdigit(s[i])) {
int k = 0;
while (i < s.size() && isdigit(s[i])) {
k = k * 10 + (s[i] - '0');
++i;
}
// s[i] is '['.
++i; // skip '['.
string encoded = decodeString(s, i);
++i; // skip ']'.
while (k > 0) {
decoded += encoded;
--k;
}
} else {
decoded.push_back(s[i++]);
}
}
return decoded;
}
};
class Solution {
public:
string decodeString(string s) {
queue<char> q;
for (int i = 0; i < s.size(); ++i) {
q.push(s[i]);
}
return decodeString(q);
}
private:
string decodeString(queue<char> &q) {
int k = 0;
string decoded;
while (!q.empty()) {
int c = q.front();
q.pop();
if (isdigit(c)) {
k = k * 10 + (c - '0');
} else if (c == '[') {
string encoded = decodeString(q);
while (k > 0) {
decoded += encoded;
--k;
}
} else if (c == ']') {
break;
} else {
decoded.push_back(c);
}
}
return decoded;
}
};
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up