Redundant Braces

Given a string A denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’.

Check whether A has redundant braces or not.

Return 1 if A has redundant braces, else return 0.

Note: A will be always a valid expression.



Input Format

The only argument given is string A.

Output Format

Return 1 if string has redundant braces, else return 0.

For Example

Input 1:
    A = "((a + b))"
Output 1:
    1
    Explanation 1:
        ((a + b)) has redundant braces so answer will be 1.

Input 2:
    A = "(a + (a + b))"
Output 2:
    0
    Explanation 2:
        (a + (a + b)) doesn't have have any redundant braces so answer will be 0.
Method:

A brace is redundant if it does not contain an operator.

Solution:

Time: O(n)
Space: O(n)

public class Solution {
    public int braces(String A) {
        Deque<Character> stack = new ArrayDeque<>();
        char[] arr = A.toCharArray();
        for (int i = 0; i < arr.length;) {
            char c = arr[i];
            if (c == '(') {
                stack.push(c);
            }
            if (c == '+' || c == '-' || c == '*' || c == '/') {
                if (!stack.isEmpty()) {
                    stack.pop();
                    while (c != ')' && c != '(') {
                        i ++;
                        c = arr[i];
                    }
                    continue;
                }
            }
            i ++;
        }
        if (stack.isEmpty()) {
            return 0;
        } else {
            return 1;
        }
    }
}