-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathRedudantParenthesis.cpp
53 lines (46 loc) Β· 1.18 KB
/
RedudantParenthesis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* Redundant Parenthesis code */
#include <bits/stdc++.h>
using namespace std;
int main(){
cout<< "Enter the string:"<<endl; // Input string
string s;
cin >> s;
stack<char> st; // stack created
bool ans = false;
for(int i=0;i<s.size();i++){
if(s[i]=='+' or s[i]=='-' or s[i]=='*' or s[i]=='/'){
st.push(s[i]); // push the operators in the stack
}else if(s[i]=='('){
st.push(s[i]); // push '(' in the stack
}else if(s[i]==')'){
if(st.top() == '('){
ans = true;
}
while(st.top() == '+' or st.top() == '-' or st.top() == '*' or st.top() == '/'){
st.pop(); // pop the operators until '(' is found
}
st.pop();
}
}
if(ans){
cout<<"True"; // if redundant
}else{
cout<<"False"; // if not redundant
}
}
/*
Input:
((a+b))
(a+(b)/c)
(a+b*(c-d))
Output:
Yes
Yes
No
Explanation:
1. ((a+b)) can reduced to (a+b), this Redundant
2. (a+(b)/c) can reduced to (a+b/c) because b is
surrounded by () which is redundant.
3. (a+b*(c-d)) doesn't have any redundant or multiple
brackets.
*/