summaryrefslogtreecommitdiff
path: root/src/main/Bracket.java
blob: e76eeba8083c9fd9093e54f3b2acf874f008b6cc (plain)
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;

public class Bracket {

    static String checkBracket(String exp) {
        Stack<Character> charStack = new Stack<>();
        int unmatchedOpeningBracket = 0;
        int count = 0;
        for (int i = 0; i < exp.length(); i++) {
            char c = exp.charAt(i);
            if (!Arrays.asList('[', ']', '(', ')', '{', '}').contains(c)) {
                count = count + 1;
                continue;
            }

            if (c == '[' || c == '(' || c == '{') {
                charStack.push(c);
                count = count + 1;
                unmatchedOpeningBracket = count;
            } else {
                if (charStack.empty())
                    return Integer.toString(i + 1);
                char top = charStack.pop();
                if ((top == '[' && c != ']') || (top == '(' && c != ')') || (top == '{' && c != '}')) {
                    return Integer.toString(i + 1);
                } else {
                    unmatchedOpeningBracket = unmatchedOpeningBracket - 1;
                }
                count = count + 1;
            }
        }
        if (charStack.empty())
            return "Success";
        else if (unmatchedOpeningBracket > 0) {
            return Integer.toString(unmatchedOpeningBracket);
        }
        return Integer.toString(count);
    }

    public static void main(String[] args) throws IOException {
        InputStreamReader input_stream = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(input_stream);
        String text = reader.readLine();

        System.out.println(checkBracket(text));
    }
}