Basic Calculator II

Basic Calculator II

问题:

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

思路:

  栈的应用,一个栈存放操作数,一个栈存放运算符

我的代码:

public class Solution {

    private Stack<Character> opers = new Stack<Character>();

    private Stack<Integer> values = new Stack<Integer>();

    public int calculate(String s)

    {

        if(s== null || s.length()==0)    return 0;

        char[] tokens = s.toCharArray();

        for(int i=0; i<tokens.length; i++)

        {

            char c = tokens[i];

            if(c == ' ') continue;

            else if(c<='9' && c>='0')

            {

                int result = 0;

                while(i<tokens.length && tokens[i] >='0' && tokens[i] <='9')

                {

                    result = result*10 + (tokens[i]-'0');

                    i++;

                }

                values.push(result);

                i--;

            }

            else if(c == '(') opers.push(c);

            else if(c == ')')

            {

                if(!opers.isEmpty() && opers.peek() != '(')

                    values.push(applyOp(opers.pop(), values.pop(), values.pop()));

                opers.pop();

            }

            else

            {

                while(!opers.isEmpty() && hasPrecedence(c, opers.peek()))

                {

                    values.push(applyOp(opers.pop(), values.pop(), values.pop()));

                }

                opers.add(c);

            }

        }

        while (!opers.empty())

        {   

            values.push(applyOp(opers.pop(), values.pop(), values.pop()));

        }

        return values.pop();

    }



    public static boolean hasPrecedence(char op1, char op2)

    {

        return op2 == '('  ? false : true; 

    }

    public static int applyOp(char op, int b, int a)

    {

        switch (op)

        {

            case '+':

                return a + b;

            case '-':

                return a - b;

        }

        return 0;

    }



}
View Code

学习之处:

  • 该题目和Basic Calculator类似,只是需要更新一下hasPrecedence和applyOp方法而已。
  • 由于在输入的过程中,已经处理了'('和‘)’,所以在hasPrecedence不用再考虑'('和')'了,把过程想明白了,自然也就清楚了。
  • 在写代码的时候,也不要一味的求简单,把所有的条件通过几个语句合并成一个语句,有的时候,把条件分割开来,一个条件一个条件的判断,也为以后的理解做的准备,也不失为一个好的解法。

你可能感兴趣的:(ca)