每日AC
来源:互联网 发布:c语言进制转换程序 编辑:程序博客网 时间:2024/05/17 01:24
每日AC - 后缀表达式计算结果-leetcode-evaluate-reverse-polish-notation
题目描述
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
昨日在地铁上看《大话数据结构》回顾下大学时光, 这个逆波兰, 有机会再奉献一份 中缀表达式变后缀的算法
后缀表达式 计算结果,抓住, 符号前来两个必须是数字, 才可以进行计算 == equals 不能乱用
AC 代码:
import java.util.Stack;/** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年6月21日 Create this file * </pre> * */public class EvalRPN { /** * 您的代码已保存 答案错误:您提交的程序没有通过所有的测试用例 case通过率为0.00% * * 测试用例: ["0","3","/"] * * 对应输出应该为: * * 0 * * 你的输出为: * * java.util.EmptyStackException * * 但是本地IDE运行没问题 ,最好的方式是将 == 变成 equals * @param tokens * @return */ public int evalRPN(String[] tokens) { int result = 0; Stack<String> s= new Stack<String>(); for(int i = 0; i <tokens.length ;i++){ if(tokens[i].equals("+") || tokens[i].equals("-") ||tokens[i].equals("*") ||tokens[i].equals("/")){ int first =Integer.parseInt(s.pop()); int second = Integer.parseInt(s.pop()); int cop = 0; if(tokens[i].equals("+")){ cop = first+second; s.push(cop+""); } else if(tokens[i].equals("-")){ cop = second - first; s.push(cop+""); }else if(tokens[i].equals("/")){ cop = second/first; s.push(cop+""); } else if(tokens[i].equals("*")){ cop = second*first; s.push(cop+""); } }else{ s.push(tokens[i]); } } result = Integer.parseInt(s.pop()); return result; } /** * @param args */ public static void main(String[] args) { String[] str = { "2", "1", "+", "3", "*" }; String[] str1 = { "4", "13", "5", "/", "+" }; String[] str2 = { "0", "3", "/" }; int ans = new EvalRPN().evalRPN(str2); System.out.println(ans); }}
阅读全文
0 0
- 每日AC
- 每日AC--leetcode--recordList
- 每日AC -数串
- 每日AC--LeetCode-Candy
- 每日AC--gas-station--LeetCode
- 每日AC-剑指offer-数组查找
- 每日AC--leetcode-- 2.Add Two Numbers
- 每日AC--POJ 1458 Common Subsequence -DP
- 每日AC--LeetCode-- wordBreak--动态规划
- 每日总结-05-19(AC自动机结束)
- 每日AC-剑指Offer -旋转数组查找最小值
- 每日AC-剑指Offer 链表中倒数第k个结点
- 每日AC-小米笔试 风口的猪-中国牛市
- 每日AC-LeetCode-palindrome-partitioning-ii --动态规划
- 每日AC--LeetCode-Triangle -- 数塔问题DP
- 每日AC--leetCode--PalindromePartitioning--回溯法 递归实现
- AC
- AC
- 全屏、沉浸式、fitSystemWindow使用及原理分析:全方位控制“沉浸式”的实现
- 记一些常用又不好记的东西
- 51nod 1594 Gcd and Phi
- Android Listview优化详解
- 用鼠标控制玩家选择的英雄转动
- 每日AC
- 对list进行分类
- Linux----网络端口
- 定义进项税代码缺省值
- 深入理解JavaScript系列
- Redis 2.8.18 安装报错 error: jemalloc/jemalloc.h: No such file or directory解决方法
- git使用时出错
- git 使用beyond compare来diff与merge
- STM32的堆与栈