[Algorithms] LeetCode 150. 逆波兰表达式求值
Categories Algorithms StackAndQueue
Tags
来源:代码随想录
栈模拟
注意string的输入输出处理,小心负数。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (string s : tokens) {
if (s == "+" || s == "-" || s == "*" || s == "/") {
char c = s[0];
int a = st.top();
st.pop();
int b = st.top();
st.pop();
if (c == '+') {
st.push(b + a);
} else if (c == '-') {
st.push(b - a);
} else if (c == '*') {
st.push(b * a);
} else {
st.push(b / a);
}
} else {
st.push(stoi(s));
}
}
return st.top();
}
};
Page views: Loading... · Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号