首页 > 其他 > 详细

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

时间:2018-06-21 10:18:51      阅读:145      评论:0      收藏:0      [点我收藏+]

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最长合法括号子串

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!