The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the eval
built-in library function.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:
由中缀表达式得到后缀表达式,再计算后缀表达式;
后缀表达式中遇到运算符时,分别得到栈顶的2个整数,再进行计算后结果入栈;
对于 +,-,*,/,( 打表入栈的优先级:若栈顶元素优先级高,则出栈,直到栈顶优先级低于插入的符号或者栈顶为'(‘。再把当前符号插入栈中。
用long long类型处理溢出;
class Solution {
public:
int k = 0;
char sign[6] = {'+','-','*','/','#','('};
int cmp[6][6]={
{1,1,0,0,1,0},
{1,1,0,0,1,0},
{1,1,1,1,1,0},
{1,1,1,1,1,0},
{0,0,0,0,1,0},
{1,1,1,1,1,0}
};
int search_sign(char s)
{
int i = 0;
for(i = 0;i<6;i++)
{
if(sign[i] == s)
return i;
}
}
string int_to_string(long long n)
{
char s[100];
memset(s,0,sizeof(s));
sprintf(s,"%lld",n);
string ss = "";
ss = ss+s;
return ss;
}
bool is_num(string s)
{
if(s[0]>= '0' && s[0]<='9')
{
return true;
}
else
return false;
}
int calculate(string s) {
stack<char> sta;
vector<string> last;//后缀表达式
sta.push('#');
string s_temp;
int i = 0;
long long a,b;
for(i = 0;i<s.length();i++)
{
//cout<<"i: "<<i<<"len: "<<s.length()<<endl;
if(s[i] == ' ')
continue;
else if(s[i] >= '0' && s[i] <= '9')
{
long long temp = s[i]-'0';
i++;
while(i<s.length() && s[i] >='0' && s[i] <='9' )
{
temp = temp * 10 + s[i]-'0';
i++;
}
i--;
last.push_back(int_to_string(temp));
}
else
{
if(s[i] == '(')
{
sta.push(s[i]);
}
else if(s[i] == ')')
{
while(!sta.empty())
{
if(sta.top()!='(')
{
s_temp = "";
s_temp = s_temp+sta.top();
last.push_back(s_temp);
sta.pop();
}
else
{
sta.pop();
break;
}
}
}
else
{
//+ ,-,*,/
while(!sta.empty())
{
if(sta.top()!='(' && cmp[search_sign(sta.top())][search_sign(s[i])] == 1)
{
s_temp = "";
s_temp = s_temp+sta.top();
last.push_back(s_temp);
sta.pop();
}
else
break;
}
sta.push(s[i]);
}
}
}
stack<long long> num;
long long sum = 0;
for(i = 0;i<last.size();i++)
{
if(is_num(last[i]))
{
num.push(atoll(last[i].c_str()));
}
else
{
a = num.top();
num.pop();
b = num.top();
num.pop();
switch(last[i][0])
{
case '+' : sum = a+b; break;
case '-' : sum = b-a; break;
case '*' : sum = b*a; break;
case '/' : sum = b/a; break;
}
num.push(sum);
}
}
while(!sta.empty())
{
if(num.size() < 2)
break;
a = num.top();
num.pop();
b = num.top();
num.pop();
//cout<<a<<" "<<b<<sta.top()<<endl;
switch(sta.top())
{
case '+' : sum = a+b; num.push(sum);break;
case '-' : sum = b-a; num.push(sum);break;
case '*' : sum = b*a; num.push(sum);break;
case '/' : sum = b/a; num.push(sum);break;
case '#' : break;
}
sta.pop();
}
return num.top();
}
};