LeetCode----32. Longest Valid Parentheses(最长有效括号)
2016-09-28 17:10
591 查看
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.
Input:"()(()"
Output:4
Expected:2
Input:"()(())"
Output:2
Expected:6
'('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.
Input:"()(()"
Output:4
Expected:2
Input:"()(())"
Output:2
Expected:6
import java.util.Deque; import java.util.LinkedList; import java.util.Stack; public class Solution { public int longestValidParentheses(String s) { // 用于记录待匹配的左括号和右括号的位置 Stack<Integer> st = new Stack<>(); int max = 0; for (int i = 0; i < s.length(); i++) { // 如是当前字符是右括号,并且记录栈非空,并且前一个字符是左括号 if (s.charAt(i) == ')' && !st.isEmpty() && s.charAt(st.peek()) == '(') { // 左括号出栈 st.pop(); // 求最大值 max = Math.max(max, i - ((st.isEmpty()) ? -1 : st.peek())); } // 其它情况就将字符入栈 else { st.push(i); } } return max; } }
相关文章推荐
- RxJava 与 Retrofit 基本使用
- Object-C 中各数据类型转换 NSData NSMutableData NSString Byte UIImage 合并音频
- 作自己
- UVa 11525 Permutation (线段树)
- java练习--输出员工信息并计算员工的工资
- 撸了一个微信小程序项目
- 撸了一个微信小程序项目
- Android addTextChangedListener(文本监听)参数解释及实现EditText字数监听
- JS加入收藏与设置主页
- [Netbeans]为面板设置背景图片
- 云镜像优化过程
- POJ 1275 Cashier Employment(差分约束系统+二分)
- Centos 系统禁ping设置
- Java7新特性
- Git
- Sample之MediaEffects
- shell中EOF等用法总结
- TCP/IP网络编程
- 关于内存分配时malloc()和calloc()的区别
- .定义两个数组,首先把两个数组合并成一个新数组,然后把新数组中的所有元素逆序排列,需要实现的效果如图-2所示。