题目地址:https://leetcode.com/problems/longest-valid-parentheses/
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int max = 0;
int from = -1;
char[] S = s.toCharArray();
for(int i = 0;i < s.length(); ++i){
if(S[i]==‘(‘) stack.push(i);
else {//S[i] == ‘)‘
if (stack.isEmpty()) from = i;//from指向最右边未匹配的‘)‘
else{
stack.pop();
if(stack.isEmpty()) max = Math.max(max,i-from);
else max = Math.max(max,i-stack.peek());
}
}
}
return max;
}
}
时间: 2024-10-12 13:47:45