解題心得
很經典的 stack 題目
程式碼
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i=0; i<tokens.size(); i++)
{
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int second = st.top(); st.pop();
int first = st.top(); st.pop();
if(tokens[i] == "+") st.push(first + second);
else if(tokens[i] == "-") st.push(first - second);
else if(tokens[i] == "*") st.push(first * second);
else if(tokens[i] == "/") st.push(first / second);
}
else
{
st.push(stoi(tokens[i]));
}
}
return st.top();
}
};
沒有留言:
張貼留言