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

思路:

1.就像题目所描述的,计算逆波兰数学表达式的结果,循环访问字符串数组类型的表达式

2.遍历的字符是数字,将数字进栈,是数学符号的时,将连续的两个数字出栈并计算出结果,然后将结果再入栈

3.重复步骤2直至所有的数组元素被访问完毕。

代码:

//代码通俗易懂,略冗余。

public int evalRPN(String[] tokens) {
        if(tokens==null||tokens.length==0)
            return 0;
        if(tokens.length==1)
            return Integer.parseInt(tokens[0]);
        int parseNum=0;
        int num1=0,num2=0;
        Stack<Integer>st=new Stack<Integer>();
        for(int i=0;i<tokens.length;i++)//iterate the item of the array
        {
        	if(isOperator(tokens[i]))//if the item is operator,caculate the numbers
        	{
        		num2=st.peek();
        		st.pop();
        		num1=st.peek();
        		st.pop();
        		parseNum=evaluteNums(num1,num2,tokens[i]);
        		if(i+1==tokens.length)
        			return parseNum;
        		st.push(parseNum);
        	}else {
				st.push(Integer.parseInt(tokens[i]));//if the item is number,push to the stack
			}
        		
        }
        return parseNum;
    }
	public int evaluteNums(int num1,int num2,String operator)
	{
		if(operator.equals("+"))
			return num1+num2;
		else if(operator.equals("-"))
			return num1-num2;
		else if(operator.equals("*"))
			return num1*num2;
		else 
			return num1/num2;
	}
	public boolean isOperator(String str)
	{
		char operator=str.charAt(0);
		if(operator=='+'||operator=='-'||operator=='*'||operator=='/')
		{
			if(str.length()==1)
				return true;
		}
		return false;
	}


你可能感兴趣的:(java,LeetCode)