Posts Parenthesis Checker (geeksforgeeks - SDE Sheet)
Post
Cancel

Parenthesis Checker (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an expression string x. Examine whether the pairs and the orders of {,},(,),[,] are correct in exp. For example, the function should return ‘true’ for exp = [()]{}{[()()]()} and ‘false’ for exp = [(]).

Note: The drive code prints “balanced” if function return true, otherwise it prints “not balanced”.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution
{
    //Function to check if brackets are balanced or not.
    static boolean ispar(String x)
    {

        Map<Character, Character> brackets = new HashMap<>();

        brackets.put(')', '(');
        brackets.put('}', '{');
        brackets.put(']', '[');

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

        for(int i=0; i<x.length(); i++){

            char ch = x.charAt(i);

            // we got a closing bracket
            if(brackets.containsKey(ch)){

                // check if it has corresponding open bracket in stack
                if(!stack.isEmpty() && brackets.get(ch) == stack.peek()){
                    stack.pop();
                }else
                    return false;

            }else{
                stack.push(ch);
            }

        }

        return stack.isEmpty();

    }
}
This post is licensed under CC BY 4.0 by the author.