您的位置:首页 > 其它

lintcode-表达式求值-368

2015-10-15 20:46 351 查看
给一个用字符串表示的表达式数组,求出这个表达式的值。

样例

对于表达式
(2*6-(23+7)/(1+2))
, 对应的数组为:

[
"2", "*", "6", "-", "(",
"23", "+", "7", ")", "/",
(", "1", "+", "2", ")"
],

其值为
2


注意 表达式只包含
整数
,
+
,
-
,
*
,
/
,
(
,
)


解题思路:


step1:把中缀表达式转换成后缀表达式


step2:通过后缀表达式求值


class Solution {
public:
void init(){
level["+"]=1;
level["-"]=1;

level["*"]=2;
level["/"]=2;

level["("]=3;
}

void step1(vector<string> &s){
for(auto &e:s){
if(e[0]<='9'&&'1'<=e[0])
ex.push_back(e);
else if(e==")"){
while(!st.empty()&&st.top()!="("){
ex.push_back(st.top());
st.pop();
}
st.pop();
}
else{
while(!st.empty()&&st.top()!="("&&level[e]<=level[st.top()]){
ex.push_back(st.top());
st.pop();
}
st.push(e);
}
}
while(!st.empty()){
ex.push_back(st.top());
st.pop();
}
}
int step2(){
for(auto &e:ex){
if(e[0]<='9'&&e[0]>='0'){
st2.push(stoi(e));
continue;
}
int a=st2.top();
st2.pop();
int b=st2.top();
st2.pop();
if(e=="+")
st2.push(b+a);
else if(e=="-")
st2.push(b-a);
else if(e=="*")
st2.push(b*a);
else
st2.push(b/a);
}
return st2.top();
}
int evaluateExpression(vector<string> &expression) {
if(expression.empty())
return 0;
init();
step1(expression);
return step2();
}
private:
stack<int>     st2;
stack<string>  st;
vector<string> ex;
map<string,int> level;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: