LeetCode_002:Evaluate Reverse Polish Notation
来源:互联网 发布:linux expec参数怎么用 编辑:程序博客网 时间:2024/05/16 09:01
package com.abuge;import java.util.Stack;/** * 需求: * 给定一组逆波兰表达式,求其表达式的值 * 思路&步骤: * 1、利用出栈和入栈实现表达式 * 2、对运算符进行判断,将字符串转换成int型,进行运算 * 3、考虑极限情况(只有一个字符串)以及减法和除法的顺序 * @author AbuGe * */public class Solution {public static int evalRPN(String[] tokens){Stack<String> stack = new Stack<String>();int len = tokens.length;int result = 0;if(len == 1){result = Integer.parseInt(tokens[0]);}else{for(int i = 0 ; i < len; i++){switch(tokens[i]){case "+":int a = Integer.parseInt(stack.pop());int b = Integer.parseInt(stack.pop());result = a + b;String str = String.valueOf(result);stack.push(str);break;case "-":a = Integer.parseInt(stack.pop());b = Integer.parseInt(stack.pop());result = b - a;str = String.valueOf(result);stack.push(str);break;case "*":a = Integer.parseInt(stack.pop());b = Integer.parseInt(stack.pop());result = (a * b);str = String.valueOf(result);stack.push(str);break;case "/":a = Integer.parseInt(stack.pop());b = Integer.parseInt(stack.pop());result = (b / a);str = String.valueOf(result);stack.push(str);break;default:stack.push(tokens[i]);break;}}}return result;}public static void main(String[] args){String[] str = {"2", "1", "+", "3", "*"};String[] str2 = {"4", "13", "5", "/", "+"};int reslut1 = evalRPN(str);System.out.println(reslut1);System.out.println("---------------------------");int result2 = evalRPN(str2);System.out.println(result2);}}
0 0
- LeetCode_002:Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 机梵蒂冈酱豆腐
- 写在开始的一些废话
- http://www.nciku.cn/pdtjhrzp517/mynciku
- 书籍推荐(部分已读)
- 全球最杰出的14位程序员
- LeetCode_002:Evaluate Reverse Polish Notation
- 学习iptables
- POJ 1002 487-3279
- 一个人安静的思考...或苦或甜、或哭或笑,长在记忆里。
- hdu1143 Tri Tiling(数学:递推)
- OpenglES Demo1
- http://www.nciku.cn/conversation/detailview?convseq=753822
- git clone cm source & cm vs android version
- Palindrome Number