Improvements in your version of code, with 100% test cases passed on GFG. class GFG { // Function to check if brackets are balanced or not. static boolean ispar(String s) { // add your code here if (s.isEmpty()) { return false; } Stack stack = new Stack(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if (c == '(' || c == '{' || c == '[') { stack.push(c); } if (stack.isEmpty()) return false; Character a; switch (c) { case ')': a = stack.pop(); if (a == '{' || a == '[') return false; break; case '}': a = stack.pop(); if (a == '(' || a == '[') return false; break; case ']': a = stack.pop(); if (a == '{' || a == '(') return false; break; } } if (stack.isEmpty()) { return true; } return false; } }
I write my code in same model but I use if else conditions to check. But I'm encountering with an error that is Bad Operand types for binary operator '== '. Can you help me!
Improvements in your version of code, with 100% test cases passed on GFG.
class GFG {
// Function to check if brackets are balanced or not.
static boolean ispar(String s) {
// add your code here
if (s.isEmpty()) {
return false;
}
Stack stack = new Stack();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
}
if (stack.isEmpty())
return false;
Character a;
switch (c) {
case ')':
a = stack.pop();
if (a == '{' || a == '[')
return false;
break;
case '}':
a = stack.pop();
if (a == '(' || a == '[')
return false;
break;
case ']':
a = stack.pop();
if (a == '{' || a == '(')
return false;
break;
}
}
if (stack.isEmpty()) {
return true;
}
return false;
}
}
Thanks
Before the for loop, we can add an if condition where if the length of the input is odd, we can return false.
Yeah, agree, if the length is off we don’t need to proceed we can return false because we are sure that its not balanced.
Thank you so much
Please do video on how to find complexity of a program in simple way
Be a pro, find it like a pro 😁
I will create one for sure atleast for time complexity
Bring more questions like this
Sure
which screen recorder and mic u r using ?
📱 only
please make a video on what all tools used by java web application developer in his day to day activities.
Sure, coming in couple of days
Its going to be out today @9 pm
@@JavaTechies thanks waiting for it.
I write my code in same model but I use if else conditions to check.
But I'm encountering with an error that is Bad Operand types for binary operator '== '.
Can you help me!
Can you share complete if condition
I think, there is a mistake in if conditions(2nd onwards) of switch case. isn't it should match the opening brackets.
If so please send updated code in comments
I will pin the code in first comment