[leetcode]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 "()()"

题意:

思路:

用Stack来辅助check Valid Parentheses

用一前一后两个指针来找longest result

代码:

 1 class Solution {
 2     public int longestValidParentheses(String s) {
 3         int result = 0;
 4         int start = -1;
 5         Stack<Integer> stack = new Stack<>(); // index of every char
 6         for(int i = 0; i < s.length(); i++){
 7             char c = s.charAt(i);
 8             if(c == '('){
 9                 stack.push(i);   
10             }else if( c == ')'){
11                 if(stack.isEmpty()){
12                     start = i;
13                 }else{
14                     stack.pop();
15                     if(stack.isEmpty()){
16                         result = Math.max(result, i - start);
17                     }else{
18                         result = Math.max(result, i - stack.peek());
19                     }
20                 }
21             }
22         }
23         return result;
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9206903.html