Given an encoded string, return it’s 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 kis guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or2[4].
Examples:
1 2 3
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
stringdecodeStringImpl(int start, int end){ string ret; int index = start; while(index < end && !isDigit(s[index]) && s[index] != ']'){ index++; } ret += s.substr(start, index - start); while (index < end) { if(!isDigit(s[index])){ int j = index; while(j < end && !isDigit(s[j])) j++; ret += s.substr(index, j - index); index = j; } else{ int leftBracket = getInt(index); int repeat = stoi(s.substr(index, leftBracket - index)); int rightBracket = findRightBracket(leftBracket); string s = decodeStringImpl(leftBracket + 1, rightBracket); for (int i = 0; i < repeat; i++) { ret += s; } index = rightBracket + 1; } } return ret; }
intfindRightBracket(int index){ vector<int> st; st.push_back(index); int i = index; while (!st.empty() && i < s.length() - 1) { i++; if (s[i] == '[') st.push_back(i); elseif (s[i] == ']') st.pop_back(); } return i; }