- Decode String
Given an expression s includes numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string.
Example
s = abc3[a] return abcaaa
s = 3[abc] return abcabcabc
s = 4[ac]dy, return acacacacdy
s = 3[2[ad]3[pf]]xyz, return adadpfpfpfadadpfpfpfadadpfpfpfxyz
Challenge
Can you do it without recursion?
思路:
这个感觉挺难。思路是用两个stack,一个维护string,一个维护number。但是不容易调通。
注意:
- 遇到’]'就把两个stack都pop出来。
- 遇到’['就把两个stack都push进去,因为新的string开始了。但要记得把num和str都clear。
- str是当前的string。topStr是之前的string,一旦topStr pop出来,要根据num (即count)来和当前的str相加。
代码如下:
class Solution {
public:
/**
* @param s: an expression includes numbers, letters and brackets
* @return: a string
*/
string expressionExpand(string &s) {
stack<int> stackNum;
stack<string> stackStr;
string result;
string str;
int num = 0;
int len = s.size();
for (int i = 0; i < len; ++i) {
if ((s[i] >= '0') && (s[i] <= '9')) {
num = num * 10 + s[i] - '0';
} else if (s[i] == ']') {
int count = stackNum.top();
stackNum.pop();
string topStr = stackStr.top();
stackStr.pop();
for (int i = 0; i < count; ++i) {
topStr += str;
}
str = topStr;
} else if (s[i] == '[') { //new str starts
stackNum.push(num);
stackStr.push(str);
num = 0;
str.clear();
} else {
str = str + s[i]; //read the letters into str
}
}
return str;
}
};