150. 逆波兰表达式求值
本题不难,但第一次做的话,会很难想到,所以先看视频,了解思路再去做题
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for (const string& token : tokens) {
if (token == "+" || token == "-" ||token == "*" || token == "/") {
long long num1 = st.top();
st.pop();
long long num2 = st.top();
st.pop();
if (token == "+") st.push(num2 + num1);
if (token == "-") st.push(num2 - num1);
if (token == "*") st.push(num2 * num1);
if (token == "/") st.push(num2 / num1);
}
else {
st.push(stoll(token)); // 将字符串转换为 long long
}
}
int result = st.top();
return result;
}
};
最开始以为和那个括号匹配本质一样的,仔细一看很多字符串怎么解决?以为是char,再仔细看是包含字符串的数组。所以