# 32. Longest Valid Parentheses

{% hint style="info" %}
Stack, java stack.empty() return bool
{% endhint %}

```java
class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> memo = new Stack<Integer>();
        int result = 0;
        for(int i = 0; i<s.length(); i++){
            
            // if current char is '(', push the index
            // if current char is ')' and the char on top of the stack is ')'
            // then it means a valid pair
            // if current char is ')',but the char on top of the stack is ')'
            // then push the index to the stack
            if(s.charAt(i)==')' && !memo.empty() && s.charAt(memo.peek()) =='('){
                memo.pop();
            }else{
                memo.push(i);
            }
        }
        
        // what's left in the stack are the indices of characters that cannot be paired 
        // the gaps (including the the gap between end of S to the first index on the stack, and the gap between the last index of the stack and the end of S) represent the length of the valid pairs.
        int currIndex = s.length();
        while(!memo.empty()){
            result = Math.max(result, currIndex - memo.peek()-1);
            currIndex = memo.pop();
        }
        result = Math.max(result, currIndex);
        return result;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ucan.gitbook.io/notes/32.-longest-valid-parentheses.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
