Exemplo n.º 1
0
  private static int evalRPN(String[] tokens) {

    Stack<String> stack = new Stack<String>();

    for (int i = 0; i < tokens.length; i++) {
      String cur = tokens[i];
      switch (cur.charAt(0)) {
        case '+':
          stack.push(String.valueOf(Integer.parseInt(stack.pop()) + Integer.parseInt(stack.pop())));
          break;
        case '-':
          int num2 = Integer.parseInt(stack.pop());
          int num1 = Integer.parseInt(stack.pop());
          stack.push(String.valueOf(num1 - num2));
          break;
        case '*':
          stack.push(String.valueOf(Integer.parseInt(stack.pop()) * Integer.parseInt(stack.pop())));
          break;
        case '/':
          int divisor = Integer.parseInt(stack.pop());
          int dividend = Integer.parseInt(stack.pop());
          stack.push(String.valueOf((Integer) (dividend / divisor)));
          break;
        default:
          stack.push(cur);
          break;
      }
    }

    return Integer.parseInt(stack.pop());
  }
Exemplo n.º 2
0
  private static boolean validParentheses(String s) {
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); i++) {
      char cur = s.charAt(i);

      if (cur == '(' || cur == '[' || cur == '{') { // Left parentheses, push into stack.
        stack.push(cur);
      } else { // Right parentheses, compare with top element of stack.
        if (stack.isEmpty())
          return false; // If stack is empty and current character is right parentheses, it is
        // invalid.
        if (samePair(stack.peek(), cur)) {
          stack.pop();
        } else {
          return false;
        }
      }
    }

    if (stack.isEmpty()) return true;
    else return false;
  }