import java.util.Stack;

class Solution {
  public int longestValidParentheses(String s) {
    var longest = 0;
    var indices = new Stack<Integer>();

    indices.push(-1);
    for (var i = 0; i < s.length(); ++i) {
      if (s.charAt(i) == '(') {
        indices.push(i);
      } else {
        indices.pop();
        if (indices.isEmpty()) {
          indices.push(i);
        } else {
          longest = Math.max(longest, i - indices.peek());
        }
      }
    }

    return longest;
  }
}