zoukankan      html  css  js  c++  java
  • LeetCode——Basic Calculator

    Description:

    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.

    用两个操作栈来处理,具体见代码。

    public class Solution {
        public static int calculate(String s) {
            Stack<Integer> num = new Stack<>();
            Stack<Character> op = new Stack<>();
            op.push('+');
            int n = s.length();
            if(n < 1) return 0;
            for(int i=0; i<n; ) {
            	if(s.charAt(i) == ' ') {
            		i ++;
            	}
            	else if(s.charAt(i) == '(') {
            		op.push('(');
            		op.push('+');
            		i ++;
            	}
            	else if(isOp(s.charAt(i))) {
            		op.push(s.charAt(i));
            		i ++;
            	}
            	//523   +-(++
            	else if(s.charAt(i) == ')') {
            		int res = 0;
                    while (!op.empty() && !(op.peek() == '(')) {  
                    	int temp = num.peek();
                    	if (op.peek() == '-') temp = -temp;
                    	res += temp;
                    	num.pop();
                    	op.pop();
                    }
                    System.out.println(res);
                    op.pop();
                    num.push(res);
                    i ++;
            	}
            	else {
            		int temp = 0;
            		while(i < n && isDigit(s.charAt(i))) {
            			temp = temp * 10;
            			temp += s.charAt(i) - '0';
            			i ++;
            		}
            		
            		num.push(temp);
            	}
            	
            }
            int res = 0;
            while (!op.empty()) {  
            	int temp = num.peek();  
            	if (op.peek() == '-') temp = -temp;  
            	res += temp;  
            	num.pop();  
            	op.pop();  
            }  
    
            return res;
            
        }
    	public static boolean isOp(char c) {
    		if(c == '+' || c == '-') {
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    	public static boolean isDigit(char c) {
    		if(c >= '0' && c <='9') {
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    }
    
  • 相关阅读:
    BGP
    物联网时代的智能家居
    Linux下找不到动态链接库
    Java清洁:终结处理和垃圾回收
    单例模式的改进
    shell脚本中的括号和实例
    shell如何生成rpm包仓库列表文件的对比结果
    shell脚本实现覆盖写文件和追加写文件
    怎么用命令查看某个目录下子目录占用空间的大小
    利用shell脚本函数实现网络连通性的检测
  • 原文地址:https://www.cnblogs.com/wxisme/p/4614848.html
Copyright © 2011-2022 走看看