码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]32. Longest Valid Parentheses最长合法括号子串

时间:2018-06-21 11:36:27      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:leetcode   题意   bsp   math   nbsp   solution   mat   input   nat   

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 }

 

[leetcode]32. Longest Valid Parentheses最长合法括号子串

标签:leetcode   题意   bsp   math   nbsp   solution   mat   input   nat   

原文地址:https://www.cnblogs.com/liuliu5151/p/9206903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!