zoukankan      html  css  js  c++  java
  • Java for LeetCode 224 Basic Calculator

    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)" = 23
    

    Note: Do not use the eval built-in library function.

    解题思路:

    只需要确定下每个括号后面需要带入的符号,用Stack即可,JAVA实现如下:

        public int calculate(String s) {
    		Stack<Integer> sign = new Stack<Integer>();
    		sign.push(1);
    		int lastOp = 1;
    		int res = 0;
    		for (int i = 0; i < s.length(); i++) {
    			switch (s.charAt(i)) {
    			case ' ':
    				break;
    			case '+':
    				lastOp = 1;
    				break;
    			case '-':
    				lastOp = -1;
    				break;
    			case '(':
    				sign.push(lastOp*sign.peek());
    				lastOp=1;
    				break;
    			case ')':
    				sign.pop();
    				break;
    			default:
    				int num = 0;
    				while (i < s.length() && Character.isDigit(s.charAt(i)))
    					num = num * 10 + s.charAt(i++) - '0';
    				i--;
    				res += lastOp * num * sign.peek();
    			}
    		}
    		return res;
        }
    
  • 相关阅读:
    0802作业1替换文本文件内容

    看病
    爬山
    作业1
    超市(未完成)
    图片复制
    替换
    文件
    英文字母和中文汉字在不同字符集编码下的字节数
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4579092.html
Copyright © 2011-2022 走看看