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 <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;
}
Solution in C++ :
In C ++ :
#include <cmath>
#include <cstdio>
#include <stack>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int t,i;
string s;
stack<char>a;
cin>>t;
while(t--){
cin>>s;
for(i=0;i<s.size();i++){
if(s[i]=='(')
a.push(s[i]);
else if(s[i]=='{')
a.push(s[i]);
else if(s[i]=='['){
a.push(s[i]);
}
else if(s[i]==')'){
if(!a.empty()){
if(a.top()=='(')
a.pop();
else
break;
}
else
break;
}
else if(s[i]=='}'){
if(!a.empty()){
if(a.top()=='{')
a.pop();
else
break;
}
else
break;
}
else if(s[i]==']'){
if(!a.empty()){
if(a.top()=='[')
a.pop();
else
break;
}
else
break;
}
}
if(a.empty()&&i==s.size())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
while(!a.empty()){
a.pop();
}
}
return 0;
}
Solution in Java :
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
//int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
Stack st = new Stack();
//arr[arr_i] = in.nextInt();
String ipSeq = in.next();
//System.out.println(ipSeq);
boolean match = true;
for(int ind=0; ind<ipSeq.length(); ind++){
char ch = ipSeq.charAt(ind);
if(ch=='(' || ch=='{' || ch=='['){
st.push(ch);
}else if(st.isEmpty()){
match = false;
break;
}else if(ch==')'){
if('('!=(char)st.pop()){
match = false;
break;
}
}else if(ch=='}'){
if('{'!=(char)st.pop()){
match = false;
break;
}
}else if(ch==']'){
if('['!=(char)st.pop()){
match = false;
break;
}
}
}
if(match){
if(!st.isEmpty()){
System.out.println("NO");
}else{
System.out.println("YES");
}
}else{
System.out.println("NO");
}
}
}
}
Solution in Python :
In Python3 :
t = int(input())
while t:
ar = ['e']
s = input()
for i in s:
if i == '(':
ar.append('(')
elif i == '[':
ar.append('[')
elif i == '{':
ar.append('{')
elif i == ')':
k = ar.pop()
if k != '(':
ar.append('k')
break
elif i == ']':
k = ar.pop()
if k != '[':
ar.append('k')
break
elif i == '}':
k = ar.pop()
if k != '{':
ar.append('k')
break
#print(ar)
if len(ar) == 0 or ar[len(ar)-1] != 'e':
print('NO')
else:
#print(len(ar), ar[len(ar)-1])
print('YES')
t-=1
View More Similar Problems
Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →