EMChamp Blog

Coding Problem | Perfectly nested String

I remember this type of lexical analysis problem being in my compilers class. That said I have never used a stack in real coding but I can see various places where O(1) read/write to latest element can be useful. This problem from codility basically asks you to check if a String is properly nested.

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

// you can also use imports, for example:
// import java.util.*;
import java.util.Stack;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
public int solution(String S) {
Stack<Character> charStack = new Stack<Character>();

for (int i=0; i < S.length(); i++) {
char c = S.charAt(i);
if(c=='{')
charStack.push('{');
else if(c=='[')
charStack.push('[');
else if(c=='(')
charStack.push('(');
else if(c=='}'){
if(charStack.peek()=='{')
charStack.pop();
else
return 0;
}
else if(c==']') {
if(charStack.peek()=='[')
charStack.pop();
else
return 0;
}
else if(c==')'){
if(charStack.peek()=='(')
charStack.pop();
else
return 0;
}
else {
System.err.println("ERROR");
return 0;
}
}

return 1;
}
}