lintcode :expression expand using C++
阿新 • • 發佈:2019-02-03
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
class Solution {
public:
/**
* @param s an expression includes numbers, letters and brackets
* @return a string
*/
string expressionExpand(string& s) {
// Write your code here
string strOut = ""; // final string to be output
string strTmp = ""; // the string between '[' and ']'
stack<int> numOfStr; //store the number of the string to be expanded
stack<char> strStore;//store the string input
int strlen = s.length();
int i = 0;
while (i < strlen)
{
int count = 0; //record the number
if (s[i] == ']' )
{
//get the string between []
while (strStore.top() != '[')
{
strTmp += strStore.top();
strStore.pop();
//pop '['
strStore.pop();
int time = numOfStr.top();
numOfStr.pop();
string strTmp2(strTmp.rbegin(), strTmp.rend());
int lenTmp = strTmp2.length();
// expand the string and push it into the stack
for (int j = 0; j < time; j++)
{
for (int k = 0; k < lenTmp; k++)
{
strStore.push(strTmp2[k]);
}
}
strTmp = "";
i++;
}
else if (isNum(s[i]) || s[i] == '[')
{
while (isNum(s[i]))
{
//get int num from char num
int numtmp = s[i] - '0';
count = count * 10 + numtmp;
i++;
}
if (s[i] == '[')
{
numOfStr.push(count);
strStore.push(s[i]);
i++;
}
}
else
{
strStore.push(s[i]);
i++;
}
}
while (!strStore.empty())
{
strOut += strStore.top();
strStore.pop();
}
//reverse the string because it is reversed as popped from stack
string strOut2(strOut.rbegin(), strOut.rend());
return strOut2;
}
//check it is number or not
bool isNum(char cr)
{
if (cr >= '0'&&cr <= '9')
return true;
else
return false;
}
};