1. You are given a string exp representing an expression.
2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other.
3. But, some of the pair of brackets maybe extra/needless.
4. You are required to print true if you detect extra brackets and false otherwise.
e.g.'
((a + b) + (c + d)) -> false
(a + b) + ((c + d)) -> true
Input Format
A string str
Output Format
true or false
Constraints
0 <= str.length <= 100
Sample Input
(a + b) + ((c + d))
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();
Stack<Character> s = new Stack<>();
int n = str.length();
boolean flag = false;
for(int i=0;i<n;i++){
char ch = str.charAt(i);
if(ch == ')'){
if(s.peek() == '('){
flag = true;
break;
}
while(s.peek() != '(')
s.pop();
s.pop();
}else
s.push(ch);
}
System.out.println(flag);
}
}
Comments
Post a Comment