Leetcode no. 32
2016-05-29 16:46
267 查看
32. Longest Valid Parentheses
Given a string containing just the characters
find the length of the longest valid (well-formed) parentheses substring.
For
which has length = 2.
Another example is
which has length = 4.
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack= new Stack<Integer>();
int max=0;
int left=-1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)=='(') stack.push(i);
else {
if (stack.isEmpty()) left=i;
else {
stack.pop();
if (stack.isEmpty()) max=Math.max(max, i-left);
else max= Math.max(max, i-stack.peek());
}
}
}
return max;
}
}
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.
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack= new Stack<Integer>();
int max=0;
int left=-1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)=='(') stack.push(i);
else {
if (stack.isEmpty()) left=i;
else {
stack.pop();
if (stack.isEmpty()) max=Math.max(max, i-left);
else max= Math.max(max, i-stack.peek());
}
}
}
return max;
}
}
相关文章推荐
- 学习进度13
- iOS开发测试不同的网络环境2G/3G/4G/WiFi
- 0529
- 记录一些插件等信息(不断更新!)
- CodeForces 591B
- eclipse有生成不带参数的构造方法的快捷键吗
- 大于零的数字以内的各个数字累加求和,奇数偶数个数,及平均值求解
- 反射-构造器
- MySQL启动本地连接服务
- 第三章 网络体系结构
- 使用superobject中的TSuperObjectHelper序列化和反序列化对象
- 苹果微信下载 iOS微信各版本列表
- CentOS 7 安装 PHP 7.0以及memcache和redis扩展
- 关于firewalld防火墙的使用
- OpenBR
- chrome有个http请求报文生成插件叫postman ,这插件在http服务接口调试时非常实用
- 设计模式之iterator
- 如何查找元素对应事件的js代码
- Android Service完全解析,关于服务你所需知道的一切(上)
- C++基础<04>—标准库vector类型