您的位置:首页 > 其它

LeetCode Longest Valid Parentheses

2015-09-17 23:24 330 查看
原题链接在这里:https://leetcode.com/problems/longest-valid-parentheses/

Given a string containing just the characters
'('
and
')'
, find the length of the longest valid (well-formed) parentheses substring.

For
"(()"
, the longest valid parentheses substring is
"()"
, which has length = 2.

Another example is
")()())"
, where the longest valid parentheses substring is
"()()"
, which has length = 4.

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

这道题是求最长的括号序列,比较容易想到用栈这个数据结构。基本思路就是维护一个栈,遇到左括号就进栈,遇到右括号则出栈,并且判断当前合法序列是否为最 长序列。不过这道题看似思路简单,但是有许多比较刁钻的测试集。具体来说,主要问题就是遇到右括号时如何判断当前的合法序列的长度。比较健壮的方式如下:
(1) 如果当前栈为空,则说明加上当前右括号没有合法序列(有也是之前判断过的);
(2) 否则弹出栈顶元素,如果弹出后栈为空,则说明当前括号匹配,我们会维护一个合法开始的起点start,合法序列的长度即为当前元素的位置 -start+1;否则如果栈内仍有元素,则当前合法序列的长度为当前栈顶元素的位置下一位到当前元素的距离,因为栈顶元素后面的括号对肯定是合法的,而 且左括号出过栈了。
因为只需要一遍扫描,算法的时间复杂度是O(n),空间复杂度是栈的空间,最坏情况是都是左括号,所以是O(n)。

Time Complexity: O(n). Space: O(n).

AC Java:

public class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0){
return 0;
}

int res = 0;
int start = 0;

Stack<Integer> stk = new Stack<Integer>();
for(int i = 0; i<s.length(); i++){
if(s.charAt(i) == '('){
stk.push(i);
}else{
//遇到')',但是stack是空的,说明不合法,更新 start 到 i+1
if(stk.isEmpty()){
start = i+1;
}else{
//否则弹出栈顶
stk.pop();
//剩下的stack为空,活命到start 到 i是合法括号对
if(stk.isEmpty()){
res = Math.max(res, i-start+1);
}else{
//身下的stack不为空,说明当前stack的栈顶 后面的括号对才是合法的
res = Math.max(res, i-stk.peek());
}
}
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: