Can anyone kindly help me improve the performance of my solution?


  • 0
    X
    public int calculate(String s) {
    	Solution stack = new Solution ();
    	s = s.replace(" ", "");
    	int index = 0;
    
    	for (int j = index; j < s.length(); j = index) {
    		String curr = String.valueOf(s.charAt(index));
    
    		// check the "+" "-" "(" operator
    		if (curr.equals("+") || curr.equals("-") || curr.equals("(")) {
    			stack.push(curr);
    			index++;
    		}
    
    		// if it is the ")"
    		else if (curr.equals(")")) {
    			int temp = 0;
    			int result = 0;
    			while (!stack.peek().equals("(")) {
    				String pop_value = stack.pop();
    				if (pop_value.equals("+")) {
    					result = result + temp;
    				} else if (pop_value.equals("-")) {
    					result = result - temp;
    				} else {
    					temp = Integer.valueOf(pop_value);
    				}
    			}
    			result = result + temp;
    			if (stack.peek().equals("(")) {
    				stack.pop();
    			}
    			stack.push(String.valueOf(result));
    			index++;
    		}
    
    		// it is a number
    		else {
    			String number;
    			StringBuilder sbuilder = new StringBuilder();
    			while (index < s.length() && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
    				sbuilder.append(s.charAt(index));
    				index++;
    			}
    			number = sbuilder.toString();
    			stack.push(number);
    		}
    
    	}
    
    	// if the fomula has no "(" ")"
    	int temp = 0;
    	int result = 0;
    	while (!stack.isEmpty()) {
    		String pop_value = stack.pop();
    		if (pop_value.equals("+")) {
    			result = result + temp;
    		} else if (pop_value.equals("-")) {
    			result = result - temp;
    		} else {
    			temp = Integer.valueOf(pop_value);
    		}
    	}
    	result = result + temp;
    	stack.push(String.valueOf(result));
    
    	return Integer.valueOf(stack.pop());
    
    }

Log in to reply
 

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