《leetCode》:Basic Calculator

来源:互联网 发布:红五图库永久域名 编辑:程序博客网 时间:2024/05/29 19:09

题目

Implement a basic calculator to evaluate a simple expression string.The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .You may assume that the given expression is always valid.Some examples:"1 + 1" = 2" 2-1 + 2 " = 3"(1+(4+5+2)-3)+(6+8)" = 23Note: Do not use the eval built-in library function.

思路

借用一个Stack,从左到右开始访问字符串,来解决。

实现代码如下:

public static int calculate(String s) {        if(s==null){            return -1;        }        int len=s.length();        int sign=1;//1:+,-1:-;        int result=0;        Stack<Integer> stack=new Stack<Integer>();//但遇到左括号时,就将之前的结果进栈        for(int i=0;i<len;i++){            char ch=s.charAt(i);            if(Character.isDigit(ch)){                int num=ch-'0';                while(i+1<len&&Character.isDigit(s.charAt(i+1))){                    num=num*10+s.charAt(i+1)-'0';                    i++;                }                result+=num*sign;            }            else if(ch=='+'){                sign=1;            }            else if(ch=='-'){                sign=-1;            }            else if(ch==' '){                continue;            }            else if(ch=='('){//进栈,保存结果                stack.push(result);                stack.push(sign);                result=0;                sign=1;            }            else if(ch==')'){//注意:先后顺序                int signInStack=stack.pop();                int tempRes=stack.pop();                tempRes+=result*signInStack;                result=tempRes;            }        }        return result;    }
1 0