0% found this document useful (0 votes)
94 views1 page

Balanced The Parentheses

The document contains code for a Solutions class with two methods: cmp() compares opening and closing brackets to check if they are a matching pair, and ispar() uses a stack to iterate through a string, pushing opening brackets and popping matching closing brackets to check if all brackets in the string are balanced.

Uploaded by

Rashmi Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views1 page

Balanced The Parentheses

The document contains code for a Solutions class with two methods: cmp() compares opening and closing brackets to check if they are a matching pair, and ispar() uses a stack to iterate through a string, pushing opening brackets and popping matching closing brackets to check if all brackets in the string are balanced.

Uploaded by

Rashmi Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solutions

{
//Function to check if opening and closing brackets are of same type.
static boolean cmp(char b, char c)
{
if(b=='{' && c=='}')
return true;
else if(b=='[' && c==']')
return true;
else if(b=='(' && c==')')
return true;
return false;
}

//Function to check if brackets are balanced or not.


static boolean ispar(String x)
{
Stack<Character> s = new Stack<>();

//iterating over the string.


for(int i=0;i<x.length();i++)
{
//if opening bracket is encountered, we push it into stack.
if(x.charAt(i)=='[' || x.charAt(i)=='{' || x.charAt(i)=='(')
s.push(x.charAt(i));

//if closing bracket is encountered, we compare it with top of stack.


else if(x.charAt(i)==']' || x.charAt(i)=='}' || x.charAt(i)==')')
{
//if top of stack has opening bracket of different
//type, we return false.
if(s.isEmpty() == true || !cmp(s.peek(),x.charAt(i)))
return false;

//else we pop the top element from stack.


else
s.pop();
}
}

//if stack becomes empty, we return true else false.


if(s.isEmpty() == true)
return true;
else
return false;
}
}

You might also like