Home > AI > Data Structure > Stack >

(HackerRank) Java Stack

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

Solution (Java)

package com.anu.game;


import java.util.*;
class Solution{

    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            String input = sc.next();
            //Complete the code


            System.out.println(isBalance(input));

        }

    }

    public static boolean isBalance(String input) {
        Stack<Character> stack = new Stack();

        for (int i=0; i<input.length(); i++) {
            char c = input.charAt(i);
            if (c == '{' || c == '[' || c == '(') {
                stack.push(c);
            } else if (c == '}') {
                if (stack.isEmpty() || stack.pop() != '{') {
                    return false;
                }
            } else if (c == ']') {
                if (stack.isEmpty() || stack.pop() != '[') {
                    return false;
                }
            } else if (c == ')') {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}



Leave a Reply