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.
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
解题思路:把数字加入stack,遇到“[",把[]里的字母加入stack, 遇到"]"以后pop out字母,然后根据数字来决定最终字母的重复次数,pop out 数字,把整理好的字母,重新加入stack, 最后把所有stack里的字母拿出。
class elemType {
public:
int num;
string str = "";
elemType(int num) {
this->num = num;
}
elemType(string str) {
this->str = str;
}
};
class Solution {
public:
string expressionExpand(string& s) {
// Write your code here
//if (s.size() == 0) {
// return NULL;
//}
int number = 0;
for (char c : s) {
if (isdigit(c)) {
number = number * 10 + (c - '0');
} else if (c == '[') {
elem.push(elemType(number));
number = 0;
} else if (c == ']') {
string popString = stackPop();
int count = elem.top().num;
//pop out number;
elem.pop();
for (int i = 0; i < count; i++) {
elem.push(elemType(popString));
}
} else {
elem.push(elemType(string(1,c)));
}
}
string result = stackPop();
return result;
}
string stackPop() {
string temp = "";
while (!elem.empty() && elem.top().str != "") {
temp = elem.top().str + temp;
elem.pop();
}
return temp;
}
private:
stack <elemType> elem;
};