首页 > 其他 > 详细

[LeetCode] 32. Longest Valid Parentheses

时间:2020-07-04 09:24:52      阅读:53      评论: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,然后创建一个start变量,暂时记为-1。记为-1的原因是有可能input从第一个字符(index = 0)开始就是有效的括号对,所以需要记成-1。接着开始遍历input

  • 遇到左括号,无条件放入stack
  • 遇到右括号,不需要将右括号入栈,但是需要做一些判断
    • 判断此时栈是否为空
      • 如果为空,则将start = i,说明有效的括号对的start index是从i开始的
      • 如果不为空,则将栈顶元素pop出来(应该会是个左括号)
        • 如果pop之后stack为空,则可以结算当前最大长度是res和i - start之间的较大者
        • 如果pop之后stack不为空,还是结算一下此时的最大长度,是res和i - stack.peek()之间的较大者

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int longestValidParentheses(String s) {
 3         // corner case
 4         if (s == null || s.length() == 0) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         Stack<Integer> stack = new Stack<>();
10         int res = 0;
11         int start = -1;
12         for (int i = 0; i < s.length(); i++) {
13             if (s.charAt(i) == ‘(‘) {
14                 stack.push(i);
15             } else {
16                 if (stack.isEmpty()) {
17                     start = i;
18                 } else {
19                     stack.pop();
20                     if (stack.isEmpty()) {
21                         res = Math.max(res, i - start);
22                     } else {
23                         res = Math.max(res, i - stack.peek());
24                     }
25                 }
26             }
27         }
28         return res;
29     }
30 }

 

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {number}
 4  */
 5 var longestValidParentheses = function(s) {
 6     // corner case
 7     if (s === null || s.length === 0) {
 8         return 0;
 9     }
10 
11     // normal case
12     let start = -1;
13     let res = 0;
14     let stack = [];
15     for (let i = 0; i < s.length; i++) {
16         if (s.charAt(i) == ‘(‘) {
17             stack.push(i);
18         } else {
19             if (stack.length === 0) {
20                 start = i;
21             } else {
22                 stack.pop();
23                 if (stack.length === 0) {
24                     res = Math.max(res, i - start);
25                 } else {
26                     res = Math.max(res, i - stack[stack.length - 1]);
27                 }
28             }
29         }
30     }
31     return res;
32 };

 

LeetCode 题目总结

[LeetCode] 32. Longest Valid Parentheses

原文:https://www.cnblogs.com/cnoodle/p/13233582.html

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