解题思路

还是用栈

提交代码

class Solution {
    public int calculate(String s) {
    	int res=0,p=0,num=0,tmp=0,flag=1;
    	Stack<Integer> stack=new Stack<Integer>();
    	
    	while(p<s.length()) {
    		if(s.charAt(p)>='0'&&s.charAt(p)<='9') {
    			num=s.charAt(p)-'0';
    			while(p+1<s.length()&&s.charAt(p+1)>='0'&&s.charAt(p)<='9') {
    				num*=10;
    				num+=s.charAt(p+1)-'0';
    				p++;
    			}
    			stack.push(flag*num);
    			flag=1;
    		}else if(s.charAt(p)=='-') {
    			flag=-1;
    		}else if(s.charAt(p)=='*') {
    			while(s.charAt(p+1)==' ') p++;
    			tmp=s.charAt(++p)-'0';
    			while(p+1<s.length()&&s.charAt(p+1)>='0'&&s.charAt(p+1)<='9') {
    				tmp*=10;
    				tmp+=s.charAt(++p)-'0';
    			}
    			res=stack.pop()*tmp;
    			stack.push(res);
    		}else if(s.charAt(p)=='/') {
    			while(s.charAt(p+1)==' ') p++;
    			tmp=s.charAt(++p)-'0';
    			while(p+1<s.length()&&s.charAt(p+1)>='0'&&s.charAt(p+1)<='9') {
    				tmp*=10;
    				tmp+=s.charAt(++p)-'0';
    			}
    			res=stack.pop()/tmp;
    			stack.push(res);
    		}
    		p++;
    	}
    	
    	res=0;
    	while(!stack.isEmpty())
    		res+=stack.pop();
    	return res;
    }
}

运行结果

【leetcode】227(Medium)Basic Calculator II

相关文章:

  • 2021-10-31
  • 2021-08-28
  • 2021-11-09
猜你喜欢
  • 2021-07-20
  • 2021-09-11
  • 2022-02-26
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
  • 2021-08-16
相关资源
相似解决方案