class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 给定一个后缀表达式,返回它的结果 * @param str string字符串 * @return long长整型 */ long long legalExp(string str) { // write code here stack<long long> s; for (int i = 0; i < str.length(); ) { if (isdigit(str[i])) { long long num = 0; while (i < str.length() && str[i] != '#') { num = num * 10 + (str[i] - '0'); i++; } s.push(num); } else if (str[i] == '+' || str[i] == '-' || str[i] == '*') { long long b = s.top(); s.pop(); long long a = s.top(); s.pop(); if (str[i] == '+') s.push(a + b); else if (str[i] == '-') s.push(a - b); else s.push(a * b); i++; } else { i++; } } return s.top(); } };