Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
题目需要实现计算器完成简单的+,-和()优先级运算,采用后缀表达式的传统方法,利用栈来完成运算过程。首先对用到的非数字的符号定义优先级,这里(优先级最高,+、-相同,=最低。对字符串的每个字符分析,当是数字的时候放入prefix字段,当是运算符时判断当前运算符与栈顶运算符的优先级比较,如果相同
class Solution {
public:
int compareSym(int a,int b)
{
//cout<<a<<" "<<b<<endl;
int flag = 0;
if(a>b)
flag = 1;
if(a<b)
flag = -1;
return flag;
}
int calculate(string s) {
map<char,int> lpri;
lpri['='] = 0;
lpri['('] = 1;
lpri['+'] = 3;
lpri['-'] = 3;
lpri[')'] = 4;
map<char,int> rpri;
rpri['='] = 0;
rpri['('] = 4;
rpri['+'] = 2;
rpri['-'] = 2;
rpri[')'] = 1;
//当当前符号在rpri中比栈顶运算符lpri的值大的时候才能进栈
//下面利用栈生成后缀表达式
string prefix;
stack<char> sym;
sym.push('=');
int i = 0;
while(s[i] != '\0')
{
if(isdigit(s[i]))
{
prefix += s[i];
while(s[i+1] !='\0'&&isdigit(s[i+1]))
prefix += s[++i];
prefix += '#';
i++;
}
else if(s[i] == ' ')
{
i++;
}
else
{
//if(s[i] != '(')
//prefix += '#';
switch(compareSym(lpri[sym.top()],rpri[s[i]]))
{
case 1:
prefix += sym.top();
sym.pop();
break;
case 0:
sym.pop();
++i;
break;
case -1:
sym.push(s[i++]);
break;
}
}
}
//prefix += '#';
while(sym.top() != '=')
{
prefix += sym.top();
sym.pop();
}
//cout<<prefix<<endl;
stack<int> number;
int j=0;
while(prefix[j] != '\0')
{
//cout<<"j:"<<j<<endl;
if(isdigit(prefix[j]))
{
string num;
num += prefix[j];
while(prefix[++j] != '#')
num += prefix[j];
stringstream ss;
ss<<num;
int temp;
ss>>temp;
//cout<<"sh:"<<temp<<endl;
number.push(temp);
}else if(prefix[j] == '#')
{
++j;
}else
{
int b = number.top();
number.pop();
int a = number.top();
number.pop();
//cout<<a<<" "<<b<<endl;
switch(prefix[j++])
{
case '+':
number.push(a+b);
break;
case '-':
number.push(a-b);
break;
}
}
}
return number.top();
}
};