Java Nesting
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
public static int nesting(String s) {
if (s.isEmpty()) {
return 1;
}
Deque<Character> stack = new ArrayDeque<>();
for (char v : s.toCharArray()) {
if (v == ')') {
if (stack.isEmpty() || stack.pop() != '(') {
return 0;
}
} else {
stack.push(v);
}
}
return stack.isEmpty() ? 1 : 0;
}
}
This treats the string like a balance counter: open parentheses add one, closing ones remove one.