For Example: Given an expression string s. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in s.
For example, the program should print ‘YES’ for s = “[()]{}{[()()]()}” and ‘NO’ for s = “[(])”
Sample Input
3
{[()]}
{[(])}
{{[[(())]]}}
Sample Output
YES
NO
YES
Explanation
- The string
{[()]}meets both criteria for being a balanced string, so we printYESon a new line. - The string
{[(])}is not balanced because the brackets enclosed by the matched pair{and}are not balanced:[(]). - The string
{{[[(())]]}}meets both criteria for being a balanced string, so we printYESon a new line.
We will use stack here to solve this problem
We have to Complete isBalanced function..
Code:
static String isBalanced(String s) {
Stack<Character> str = new Stack();
String ans = "YES";
String no = "NO";
boolean answer = true;
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(ch == '{' || ch == '[' || ch == '('){
str.push(ch);
continue;
}
if(str.isEmpty()){
return no;
}
if(ch == ')'){
if(str.peek() == '('){
str.pop();
}else{
answer = false;
break;
}
}
if(ch == ']'){
if(str.peek() == '['){
str.pop();
}else{
answer = false;
break;
}
}
if(ch == '}'){
if(str.peek() == '{'){
str.pop();
}else{
answer = false;
break;
}
}
}
if(!str.isEmpty()){
answer = false;
}
if(answer)
return ans;
else
return no;
}
Thank You!
Happy Coding Friends!
rendi kaunsi language hai yo
sc st language mc
LikeLiked by 1 person