您的位置:首页 > 其它

[LeetCode]32 Longest Valid Parentheses

2015-01-02 16:39 295 查看
https://oj.leetcode.com/problems/longest-valid-parentheses/
http://fisherlei.blogspot.com/2013/03/leetcode-longest-valid-parentheses.html
http://rleetcode.blogspot.com/2014/01/longest-valid-parentheses.html
public class Solution {
public int longestValidParentheses(String s) {

if (s == null || s.isEmpty())
return 0;   // Invalid input

Stack<Integer> stack = new Stack<>();

int max = 0;
int last = -1;

char[] chars = s.toCharArray();
int len = chars.length;
for (int i = 0 ; i < len ; i ++)
{
if (chars[i] == '(')
{
stack.push(i);
}
else // ')', assuming no other char
{
if (stack.empty())
{
last = i;
continue;   // invalid
}

stack.pop();
if (stack.isEmpty())
{
// 如果stack是空,那么从上一个invalid位置到i都valid
// 即 i - (last + 1) + 1
max = Math.max(max, i - (last + 1) + 1);
}
else
{
// 如果stack 不为空, 那么从上一个 '(' 之后到i都valid
// 即 i - (stack.peek() + 1) + 1
max = Math.max(max, i - (stack.peek() + 1) + 1);
}
}
}

return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode