求解逆波兰表达式
evaluate-reverse-polish-notation
http://www.nowcoder.com/questionTerminal/22f9d7dd89374b6c8289e44237c70447
刚开始判断条件没弄明白,绕了一圈,呜呜
//
// Created by jt on 2020/8/7.
//
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
/**
*
* @param tokens string字符串vector
* @return int整型
*/
int evalRPN(vector <string> &tokens) {
// write code here
// 什么是逆波兰式——数字和运算符组成的二叉树的后序遍历,叶节点为数字,非叶节点为运算符
stack<int> op;
for (int i = 0; i < tokens.size(); ++i) {
string current = tokens[i];
// 注意,这里的条件不能判断数字,因为数字可能含有正负号
if (current == "+" || current == "-" || current == "*" || current == "/") {
if (op.size() < 2){ // 如果栈里面没有两个数了,返回0
return 0;
}
int b = op.top();
op.pop();
int a = op.top();
op.pop();
if (tokens[i] == "+") {
op.push(a + b);
} else if (tokens[i] == "-") {
op.push(a - b);
} else if (tokens[i] == "*") {
op.push(a * b);
} else {
op.push(a / b);
}
} else {
op.push(stoi(current));
}
}
return op.top();
}
};刷遍天下无敌手 文章被收录于专栏
秋招刷题历程
查看11道真题和解析