Given a valid arithmetic expression as a string, check if it contains any redundant braces. A set of braces is redundant if the subexpression inside it does not require the braces (i.e., there are no operators inside the braces).
Return:
1 if redundant braces are present
0 if not
The expression will only contain +, -, *, /, parentheses, and lowercase letters.
Use a stack to track parentheses and operators. If a closing parenthesis is found and there are no operators between the matching opening and closing parenthesis, the braces are redundant.
classSolution {
public:int braces(string A) {
stack<char> st;
for (char c : A) {
if (c =='('|| c =='+'|| c =='-'|| c =='*'|| c =='/') {
st.push(c);
} elseif (c ==')') {
if (st.top() =='(') return1;
while (!st.empty() && st.top() !='(') st.pop();
st.pop();
}
}
return0;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintbraces(String A) {
Stack<Character> stack =new Stack<>();
for (int i = 0; i < A.length(); i++) {
char c = A.charAt(i);
if (c =='('|| c =='+'|| c =='-'|| c =='*'|| c =='/') {
stack.push(c);
} elseif (c ==')') {
if (stack.peek() =='(') return 1;
while (!stack.isEmpty() && stack.peek() !='(') stack.pop();
stack.pop();
}
}
return 0;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defbraces(self, A: str) -> int:
st = []
for c in A:
if c in'()+-*/':
st.append(c)
elif c ==')':
if st and st[-1] =='(': return1while st and st[-1] !='(': st.pop()
if st: st.pop()
return0