逆波兰表达式求值思路:从左到右遍历表达式,遇见数字则进栈,遇见字符则弹出栈顶的两数字计算,计算结果进栈。
int lev(string s)
{
if(s=="+")
return 0;
else if(s=="-")
return 1;
else if(s=="*")
return 2;
else if(s=="/")
return 3;
return 4;
}
int evalRPN(vector<string> &tokens) {
// write your code here
stack<int>st;
string item;
int ch1,ch2,a;
int anser,num;
for(int i=0;i<tokens.size();i++)
{
item=tokens[i];
num=lev(item);
switch(num){
case 0:ch1=st.top();st.pop();ch2=st.top();st.pop();anser=ch2+ch1;
st.push(anser);break;
case 1:ch1=st.top();st.pop();ch2=st.top();st.pop();anser=ch2-ch1;
st.push(anser);break;
case 2:ch1=st.top();st.pop();ch2=st.top();st.pop();anser=ch2*ch1;
st.push(anser);break;
case 3:ch1=st.top();st.pop();ch2=st.top();st.pop();anser=ch2/ch1;
st.push(anser);break;
case 4: st.push(atoi(tokens[i].c_str()));break;
//atoi() 将字符串转为整数
}
}
anser=st.top();
return anser;
}
case处的代码多余重复了,显得很难看。修改一下,看起来舒服很多,如下:
int lev(string s)
{
if(s=="+")
return 0;
else if(s=="-")
return 1;
else if(s=="*")
return 2;
else if(s=="/")
return 3;
return 4;
}
int evalRPN(vector<string> &tokens) {
// write your code here
stack<int>st;
int ch1,ch2;
int anser,num;
for(int i=0;i<tokens.size();i++)
{
num=lev(tokens[i]);
if(num == 4)
st.push(atoi(tokens[i].c_str()));
else
{
ch1=st.top();
st.pop();
ch2=st.top();
st.pop();
if(num == 0)
anser=ch2+ch1;
else if(num == 1)
anser=ch2-ch1;
else if(num == 2)
anser=ch2*ch1;
else if(num == 3)
anser=ch2/ch1;
st.push(anser);
}
}
anser=st.top();
return anser;
}
atoi(tokens[i].c_str()) :
atoi() 把字符串转成整形数
c_str() 返回字符串的地址