public int longestValidParentheses(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        List<int[]> spans = new LinkedList<>();

        Deque<Integer> deque = new LinkedList<>();
        int maxSpan = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '(') {
                deque.add(i);
            } else if (c == ')') {
                Integer start = deque.pollLast();

                if (start != null) {
                    insert(spans, new int[] { start, i });
                }
            }
        }

        for (int[] span : spans) {
            int len = span[1] - span[0];
            if (len > maxSpan) {
                maxSpan = len + 1;
            }
        }

        return maxSpan;
    }