给一个用字符串表示的表达式数组,求出这个表达式的值。
表达式只包含整数, +, -, *, /, (, )
static bool cmp[][7] =
{
{0,0,0,0,0,0,0},
{1,1,1,0,0,0,1},
{1,1,1,0,0,0,1},
{1,1,1,1,1,0,1},
{1,1,1,1,1,0,1},
{1,0,0,0,0,0,1},
{1,0,0,0,0,0,0}
};
static const vector<string> operators = {"#", "+", "-", "*", "/", "(", ")"};
int evaluateExpression(vector<string> &expression) {
static unordered_map<string, int> hash;
for (int i = 0; i < operators.size(); ++i) {
hash[operators[i]] = i;
}
vector<int> optr(1, 0); // expression extended to "#" expression "#"
vector<double> oprd;
expression.push_back("#");
for (auto e : expression) {
auto iter = hash.find(e);
if (iter == hash.end()) {
oprd.push_back(atoi(e.c_str()));
continue;
}
int idx = iter->second;
while (true) {
int prior = optr.back();
if (!cmp[prior][idx]) {
optr.push_back(idx);
break;
}
optr.pop_back();
if (prior == 5) { break; }
double b = oprd.back();
oprd.pop_back();
double a = oprd.back();
oprd.pop_back();
switch (prior) {
case 1 :
oprd.push_back(a + b);
break;
case 2 :
oprd.push_back(a - b);
break;
case 3 :
oprd.push_back(a * b);
break;
case 4 :
oprd.push_back(a / b);
break;
}
}
}
return oprd.empty() ? 0 : static_cast<int>(oprd.back());
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。