Balanced Brackets
Problem Statement :
A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]. By this logic, we say a sequence of brackets is balanced if the following conditions are met: It contains no unmatched brackets. The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO. Function Description Complete the function isBalanced in the editor below. It must return a string: YES if the sequence is balanced or NO if it is not. isBalanced has the following parameter(s): s: a string of brackets Input Format The first line contains a single integer n, the number of strings. Each of the next n lines contains a single string s, a sequence of brackets. Output Format For each string, return YES or NO.
Solution :
Solution in C :
In C ++ :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<stack>
using namespace std;
#include<map>
int main() {
map<char,char>lol;
lol[')']='(';
lol[']']='[';
lol['}']='{';
int t;
cin >> t;
while(t--)
{
string s;
stack<char>st;
cin >> s;
int flag=0;
for(int i=0;s[i]!='\0';i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
st.push(s[i]);
else{
if(!st.empty() and lol[s[i]]==st.top())
st.pop();
else
{
flag=1;
break;
}
}
}
if(!flag and st.empty())
cout << "YES" << endl;
else
cout << "NO " << endl;
}
return 0;
}
In Java :
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
int numTest = Integer.parseInt(sc.nextLine());
for(int i = 0; i < numTest; i++){
if(isBalanced(sc.nextLine())){
System.out.println("YES");
} else {
System.out.println("NO");
}
}
} catch(Exception e){
System.out.println("Invalid Input");
}
}
public static boolean isBalanced(String s){
if(s == null || s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == '(' || c == '{' || c == '['){
stack.push(c);
} else if(c == ')' || c == '}' || c == ']'){
if(!stack.isEmpty()){
char latestOpenP = stack.pop();
if(latestOpenP == '(' && c != ')'){
return false;
} else if(latestOpenP == '{' && c != '}'){
return false;
} else if(latestOpenP == '[' && c != ']'){
return false;
}
} else {
return false;
}
}
}
return stack.isEmpty();
}
}
In C :
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int same(char a,char b)
{
if(a=='['&& b==']')
return 1;
if(a=='{'&& b=='}')
return 1;
if(a=='('&& b==')')
return 1;
return 0;
}
int check(char *a)
{
char stack[1001],top=-1;
for(int j=0;j<strlen(a);j++)
{
if(a[j]=='['||a[j]=='{'||a[j]=='(')
stack[++top]=a[j];
if(a[j]==']'||a[j]=='}'||a[j]==')')
{
if(top==-1)
{
return 0;
}
else
{
if(!same(stack[top--],a[j]))
{
return 0;
}
}
}
}
if(top!=-1)
{
return 0;
}
return 1;
}
int main() {
char a[1001];
int n,valid;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",a);
valid = check(a);
if(valid==1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
In Python3 :
#! /usr/bin/python3
def check():
stack = []
s = input()
for c in s:
#print(c)
if c == '(':
stack.append(0);
elif c == ')':
if len(stack) > 0 and stack[-1] == 0:
stack.pop()
else:
return -1
elif c == '[':
stack.append(2)
elif c == ']':
if len(stack) > 0 and stack[-1] == 2:
stack.pop()
else:
return -1
if c == '{':
stack.append(4)
elif c == '}':
if len(stack) > 0 and stack[-1] == 4:
stack.pop()
else:
return -1
if len(stack) == 0:
return 0
else:
return -1
def solve():
t = int(input())
for i in range(0,t):
if check() == 0:
print("YES")
else:
print("NO")
solve()
View More Similar Problems
Balanced Brackets
A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra
View Solution →Equal Stacks
ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of
View Solution →Game of Two Stacks
Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f
View Solution →Largest Rectangle
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle
View Solution →Simple Text Editor
In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,
View Solution →Poisonous Plants
There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan
View Solution →