第三题 Java 版
给定字符串, 计算其中的结果,就是那种表达式计算的题
一般思路: 创建两个栈, 一个存储操作数, 一个存储操作符,每次遇到操作符, 取出两个数进行计算。然后存回操作数栈中。
这题使用一个栈就行了, 因为这个不用考虑运算符优先级, 先在前面的运算符优先运算。
模拟。
AC Code
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 给定一个后缀表达式,返回它的结果 * @param str string字符串 * @return long长整型 */ public long solve (String str) { // write code here Stack<Long> s = new Stack<>(); Stack<String> op = new Stack<>(); char[] cs = str.toCharArray(); long temp = 0; for(int i = 0; i < cs.length; i++){ if(cs[i] == '#'){ s.add(temp); temp = 0; continue ; } if(cs[i] >= '0' && cs[i] <= '9'){ temp = temp * 10 + (cs[i] - '0'); } else { // 操作符 // 取出两个数 long a = s.pop(); long b = s.pop(); long res = 0; if(cs[i] == '+'){ res = a + b; }else if(cs[i] == '-'){ res = (b - a); } else if(cs[i] == '*'){ res = (a * b); } // 回栈 s.add(res); } } return s.pop(); } }