Balanced Brackets Hackerrank Solution

For Example: Given an expression string s. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in s.
For example, the program should print ‘YES’ for s = “[()]{}{[()()]()}” and ‘NO’ for s = “[(])”

Sample Input

3
{[()]}
{[(])}
{{[[(())]]}}

Sample Output

YES
NO
YES

Explanation

  1. The string {[()]} meets both criteria for being a balanced string, so we print YES on a new line.
  2. The string {[(])} is not balanced because the brackets enclosed by the matched pair { and } are not balanced: [(]).
  3. The string {{[[(())]]}} meets both criteria for being a balanced string, so we print YES on a new line.

We will use stack here to solve this problem

We have to Complete isBalanced function..

Code:

static String isBalanced(String s) {
        Stack<Character> str = new Stack();
        String ans = "YES";
        String no = "NO";
        boolean answer = true;
        for(int i=0; i<s.length(); i++){
            char ch = s.charAt(i);
            if(ch == '{' || ch == '[' || ch == '('){
                str.push(ch);
                continue;
            }
            if(str.isEmpty()){
                return no;

            }
            if(ch == ')'){
                if(str.peek() == '('){
                    str.pop();
                }else{
                    answer = false;
                    break;
                }
            }
            if(ch == ']'){
                if(str.peek() == '['){
                    str.pop();
                }else{
                    answer = false;
                    break;
                }
            }
            if(ch == '}'){
                if(str.peek() == '{'){
                    str.pop();
                }else{
                    answer = false;
                    break;
                }
            }
            

        }
        if(!str.isEmpty()){
                answer = false;
            }
            if(answer)
            return ans;
            else
            return no;


    }

Thank You!

Happy Coding Friends!



Categories: HackerRank Questions

Tags: , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: