LeetCode Longest Valid Parentheses

来源:互联网 发布:js中控制div隐藏 编辑:程序博客网 时间:2024/05/29 17:52

原题链接在这里:https://leetcode.com/problems/longest-valid-parentheses/

Largest Rectangle in Histogram都是往栈内存index. 

生成一个stack, 从头往后扫string, 遇到'(', 就把当前index存入到stack中。

当遇到 ')'时要看当前stack是后为空,若为空,更新新起点start = i+1;

若不为空,就pop出来一个index,然后再看stack是否为空:

若为空,则最大长度maxLength更新为Math.max(maxLength, i-start+1);

若不为空,则maxLength更新为Math.max(maxLength,i-stk.peek()), 因为"( ( )"返回的长度是3不是2. 这里的三个括号配对是合法的。

Time O(n), Space O(n).

AC Java:

public class Solution {    public int longestValidParentheses(String s) {        if(s == null || s.length() == 0){            return 0;        }        Stack<Integer> stk = new Stack<Integer>();        int maxLength = 0;        int start = 0;        for(int i = 0; i<s.length(); i++){            if(s.charAt(i) == '('){                stk.push(i);            }            else{                if(stk.isEmpty()){                    start = i+1;                }else{                    int index = stk.pop();                    if(stk.isEmpty()){                        maxLength = Math.max(maxLength, i-start+1);                    }else{                        maxLength = Math.max(maxLength, i-stk.peek());                    }                }            }        }        return maxLength;    }}


0 0
原创粉丝点击