1. You are given a string exp representing an expression.
2. You are required to check if the expression is balanced i.e. closing brackets and opening brackets match up well.
e.g.
[(a + b) + {(c + d) * (e / f)}] -> true
[(a + b) + {(c + d) * (e / f)]} -> false
[(a + b) + {(c + d) * (e / f)} -> false
([(a + b) + {(c + d) * (e / f)}] -> false
Input Format
A string str
Output Format
true or false
Constraints
0 <= str.length <= 100
Sample Input
[(a + b) + {(c + d) * (e / f)}]
Sample Output
true
Solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int n = str.length();
Stack<Character> s = new Stack<>();
for(int i=0;i<n;i++){
char ch = str.charAt(i);
if(ch == '[')
s.push(']');
else if(ch == '{')
s.push('}');
else if(ch == '(')
s.push(')');
else if(ch == '}' || ch == ']' || ch == ')'){
if(!s.empty() && s.peek() == ch)
s.pop();
else{
System.out.println(false);
return;
}
}
}
if(s.empty())
System.out.println(true);
else
System.out.println(false);
}
}
Comments
Post a Comment