Evaluate Reverse Polish Notation(LeetCode)

题目:

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


思路:

这题比较简单。可以通过一个栈实现。

  1. 从左到右遍历所给的字符串数组
    • 如果遇到的是数字,把数字push进栈中
    • 如果遇到的是运算符
      • 将两个数字从栈中pop出来记为做操作数lnum和右操作数rnum(注意先pop出的是右操作数,顺序不能反)
      • 将lnum和rnum进行运算后,结果push到栈中
  2. 重复1,直到遍历完成
  3. 最后,栈中只有一个数字,为最后结果。pop处后返回
注意点:
  1. 栈中pop出的元素的类型转换
    • pop出的是object类型,需要用大写全称来转换(int -->Integer byte-->Byte short-->Short long -->Long float-->Float double-->Double boolean-->Boolean char-->Character)
    • 例如:已经push进一个整形,s.push(1); 需要int m = (Integer) s.pop();
  2. Java栈的使用
    • 栈在util包中,使用前需要 import java.util.*;
    • 简单类型、引用类型都可以入栈
  3. 字符串相同的判断
    • 使用if(notation == "/")时,在LeetCode上运行总是有runtime错误(在eclipse上却可以通过相同的输入)
    • 改用if(notation.equals("/"))时,就可以通过了
    • 以后字符串的相同判断尽量用(s.euqals("string"))??

代码:

import java.util.*;//Stack类在util包中

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack s = new Stack(); //注意栈的创建方式
        int lnum, rnum, result;
        for (int i=0; i < tokens.length; i++){
            String notation = tokens[i];//notaion记录当前字符串
            if (notation.equals("+")){//字符串相同判断用equals方法比较好?
                rnum = (Integer) s.pop();//出栈需要用大写全称转换类型
                lnum = (Integer) s.pop();
                result = lnum + rnum;
                s.push(result);
            }else if (notation.equals("-")){
                rnum = (Integer) s.pop();
                lnum = (Integer) s.pop();
                result = lnum - rnum;
                s.push(result);
            }else if (notation.equals("*")){
                rnum = (Integer) s.pop();
                lnum = (Integer) s.pop();
                result = lnum * rnum;
                s.push(result);
            }else if (notation.equals("/")){
                rnum = (Integer) s.pop();
                lnum = (Integer) s.pop();
                result = lnum / rnum;
                s.push(result);
            }else {
                rnum = Integer.valueOf(notation);//字符串转换成数字的方法
                s.push(rnum);
            }
        }
        result = (Integer) s.pop();
        return result;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值