biryu2205 / Biryu

0 stars 0 forks source link

Hackerrank Java Stack #94

Closed biryu2205 closed 6 years ago

biryu2205 commented 7 years ago
import java.util.Scanner;
import java.util.Stack;

public class Solution {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
      System.out.println(isBalanced(sc.next()));
    }
    sc.close();
  }

  static boolean isBalanced(String parentheses) {
    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < parentheses.length(); i++) {
      char ch = parentheses.charAt(i);
      if (ch == '(' || ch == '[' || ch == '{') {
        stack.push(ch);
      } else if (stack.empty()) {
        return false;
      } else {
        char top = stack.pop();
        if ((top == '(' && ch != ')') || (top == '[' && ch != ']')
            || (top == '{' && ch != '}')) {
          return false;
        }
      }
    }
    return stack.empty();
  }
}

Link https://www.hackerrank.com/challenges/java-stack/problem