题解 | 牛牛与后缀表达式
牛牛与后缀表达式
https://www.nowcoder.com/practice/a1a4f178f6ff4188890e51da1cc8ce10
import java.util.*;
public class Solution {
/**
* 给定一个后缀表达式(数字用 # 分隔),返回它的结果
* @param str string字符串
* @return long长整型
*/
public long legalExp (String str) {
Stack<Long> stack = new Stack<>();
int n = str.length();
int i = 0;
while (i < n) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
// 解析一个完整的数字,直到遇到 '#'
StringBuilder num = new StringBuilder();
while (i < n && Character.isDigit(str.charAt(i))) {
num.append(str.charAt(i));
i++;
}
if (i < n && str.charAt(i) == '#') {
i++; // 跳过 '#'
}
stack.push(Long.parseLong(num.toString()));
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
long b = stack.pop();
long a = stack.pop();
long res = 0;
switch (c) {
case '+': res = a + b; break;
case '-': res = a - b; break;
case '*': res = a * b; break;
case '/': res = a / b; break;
}
stack.push(res);
i++; // 运算符只占 1 个字符
} else {
// 其他符号直接跳过
i++;
}
}
return stack.pop();
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.legalExp("12#3#+15*")); // 输出 225
}
}

查看1道真题和解析