Java Solution using stack


  • 0
    O

    public class Solution {
    private Stack stack = new Stack();

    public int calculate(String s) {
    	int all = 0;
    	for (int i = 0; i < s.length(); ++i) {
    		if (s.charAt(i) == ' ') {
    			continue;
    		} else if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
    			int j = i + 1;
    			if(j!=s.length()){
    				while (s.charAt(j) >= '0' && s.charAt(j) <= '9') {
    					j++;
    					if(j==s.length())
    						break;
    				}
    			}
    			stack.push(String.valueOf(s.substring(i, j)));
    			i = j - 1;
    		} else if (s.charAt(i) == ')') {
    			int result = 0;
    			while (!stack.peek().equals('(')) {
    				String valueStr = (String) stack.pop();
    				int value=Integer.valueOf(valueStr);
    				char sign = '+';
    				if (!stack.peek().equals('(')) {
    					sign = (Character) stack.pop();
    				}
    				switch (sign) {
    				case '+':
    					result = result + value;break;
    				case '-':
    					result = result - value;break;
    				}
    			}
    			stack.pop();
    			stack.push(String.valueOf(result));
    		} else {
    			stack.push(s.charAt(i));
    		}
    
    	}
    	while (!stack.isEmpty()) {
    		String valueStr = (String) stack.pop();
    		int value=Integer.valueOf(valueStr);
    		char sign = '+';
    		if (!stack.isEmpty()) {
    			sign = (Character) stack.pop();
    		}
    		switch (sign) {
    		case '+':
    			all = all + value;
    			break;
    		case '-':
    			all = all - value;
    			break;
    		}
    	}
    	return all;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.