Description:
Add to List
Share
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Solution:
思路:左括號push,右括號pop,如果為空則pop後繼續插入。使得每次操作後至少有一個值在stack中。
最後只需要當前下標減去棧頂的值就是當前匹配長度。
public int longestValidParentheses(String s) {
int max = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for(int i = 0; i < s.length(); ++i) {
if(s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if(stack.empty()) {
stack.push(i);
} else {
max = Math.max(max, i - stack.peek());
}
}
}
return max;
}