394 Decode String
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".string go(string s, int &pos)
{
string mult_s = ""; // default multiplier
string word = ""; // default substr
for (; pos < s.length(); pos++) {
if (s[pos] == '[') {
string sub_word = go(s, ++pos);
int mult_i = stoi(mult_s.c_str());
for (mult_i; mult_i > 0; mult_i--)
word += sub_word;
mult_s = "";
}
else if (s[pos] == ']')
return word;
else if (isalpha(s[pos]))
word += s[pos];
else if (isdigit(s[pos]))
mult_s += s[pos];
}
return word;
}
string decodeString(string s)
{
int pos = 0;
return go(s, pos);
}Brain Storm
Last updated