Balanced Brackets in java

Balanced Brackets in java

Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is Balanced if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order.

Input:

The first line contains a single integer n(Length of the string) The second line contains string s

Output:

Print YES is brackets are balanced otherwise print NO

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
Sample Input 1
2
()
Sample Output 1

YES

Sample Input 2
2
(]
Sample Output 2
NO

Solution of Balanced Brackets in java:–

import java.util.*;
import java.io.*;
 
public class Main {
    static String s;
    static Stack<Character> stack = new Stack<>();
    public static boolean check(int i){
        if(stack.empty())
            return true;
        if(stack.peek() == '(' && s.charAt(i) == ')')
            return false;
        if(stack.peek() == '[' && s.charAt(i) == ']')
            return false;
        if(stack.peek() == '{' && s.charAt(i) == '}')
            return false;
        return true;
    }
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        s = input.next();
        for(int i = 0; i < n; i++){
            if(check(i)){
                stack.push(s.charAt(i));
            }else{
                stack.pop();
            }
        }
        if(stack.empty()){
            System.out.println("YES");
        }else{
            System.out.println("NO");
        }
    }
}

Add a Comment

Your email address will not be published. Required fields are marked *