32. Longest Valid Parentheses
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 "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
https://www.youtube.com/watch?v=M1Vw5Tk1rw4&t=99s
http://bangbingsyb.blogspot.com/2014/11/leetcode-longest-valid-parentheses.html
// steps are according to youtube example
class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() < 2) return 0;
int n = s.length();
int max = 0;
int leftMost = -1;
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; i++){
if(s.charAt(i) == '('){
stack.push(i);
}else{
// )
if(stack.isEmpty()){
// util here, not a valid parenthese
leftMost = i;
}else{
int j = stack.pop();
if(stack.isEmpty()){
max = Math.max(max, i - leftMost);
}else{
max = Math.max(max, i - stack.peek());
}
}
}
}
return max;
}
}
posted on 2018-11-08 02:31 猪猪🐷 阅读(126) 评论(0) 收藏 举报
浙公网安备 33010602011771号