Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Created September 9, 2016 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclipselu/0af47dfe6deac693e6e80238d95fe6a8 to your computer and use it in GitHub Desktop.
Save eclipselu/0af47dfe6deac693e6e80238d95fe6a8 to your computer and use it in GitHub Desktop.
Decode String
class Solution {
public:
string decodeString(string s) {
int len = s.length();
if (len == 0)
return s;
stack<int> num_st;
stack<string> sym_st;
int i = 0;
bool lastIsNum = false;
while (i < len) {
if (isdigit(s[i])) {
int num = 0;
if (lastIsNum && !num_st.empty()) {
num = num_st.top();
num_st.pop();
}
num *= 10;
num += (s[i] - '0');
num_st.push(num);
lastIsNum = true;
}
else if (s[i] == '[') {
sym_st.push(string(1, s[i]));
lastIsNum = false;
}
else if (s[i] == ']') {
int k = num_st.top();
num_st.pop();
string str = "";
// merge strings in []
while (!sym_st.empty() && sym_st.top() != "[") {
str = sym_st.top() + str;
sym_st.pop();
}
sym_st.push(str);
// repeat
for (int i = 0; i < k - 1; ++i)
str = sym_st.top() + str;
sym_st.pop(); // pop string in []
sym_st.pop(); // pop [
sym_st.push(str);
lastIsNum = false;
}
else {
string str = string(1, s[i]);
while (!sym_st.empty() && sym_st.top() != "[") {
str = sym_st.top() + str;
sym_st.pop();
}
sym_st.push(str);
lastIsNum = false;
}
++i;
}
while (sym_st.size() > 1) {
string top = sym_st.top();
sym_st.pop();
top = sym_st.top() + top;
sym_st.pop();
sym_st.push(top);
}
return sym_st.top();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment