Valid Parentheses & Longest Valid Parentheses
2016-07-13 11:03
253 查看
Valid Parentheses
Given a string containing just the characters
Example
The brackets must close in the correct order,
分析:
使用stack来保存每个括号,如果最上面的和当前括号匹配,则除去最上面的括号,否则把新括号加入。如果最后stack为空,则所有括号匹配。
Longest Valid Parentheses
Given a string containing just the characters
For
Another example is
Given a string containing just the characters
'(', ')',
'{',
'}',
'['and
']', determine if the input string is valid.
Example
The brackets must close in the correct order,
"()"and
"()[]{}"are all valid but
"(]"and
"([)]"are not.
分析:
使用stack来保存每个括号,如果最上面的和当前括号匹配,则除去最上面的括号,否则把新括号加入。如果最后stack为空,则所有括号匹配。
public class Solution { /** * @param s A string * @return whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { if (s == null || s.length() % 2 == 1) return false; Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (stack.size() == 0) { stack.push(s.charAt(i)); } else { char c1 = stack.peek(); char c2 = s.charAt(i); if (c1 == '(' && c2 == ')' || c1 == '[' && c2 == ']' || c1 == '{' && c2 == '}') { stack.pop(); } else { stack.push(s.charAt(i)); } } } return stack.isEmpty(); } }
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.
public class Solution { public static int longestValidParentheses(String str) { if (str == null || str.length() == 0) return 0; int max = 0; int total = 0; int numberofLeftParentheses = 0; for (int k = 0; k < str.length(); k++) { if (str.charAt(k) == '(') { numberofLeftParentheses++; } else { numberofLeftParentheses--; } total++; if (numberofLeftParentheses == 0 && max < total) { max = total; } if (numberofLeftParentheses < 0) { total = 0; numberofLeftParentheses = 0; } } total = 0; numberofLeftParentheses = 0; for (int k = str.length() - 1; k >= 0; k--) { if (str.charAt(k) == ')') { numberofLeftParentheses++; } else { numberofLeftParentheses--; } total++; if (numberofLeftParentheses == 0 && max < total) { max = total; } if (numberofLeftParentheses < 0) { total = 0; numberofLeftParentheses = 0; } } return max; } }
相关文章推荐
- Myeclipse2014找不到Help-->install new software
- 记一次基于Unity的Profiler性能分析
- Java的泛型
- Hadoop学习笔记:MapReduce框架详解
- 微信扫码登陆过程。
- SSD:Single Shot MultiBox Detector 心得 (持续更新中。。。)
- 用html、jquery、php编写新闻后台管理页面,动态添加新闻数据并实现数据的增删改查功能
- Java性能优化指南系列(三):理解JIT编译器
- javascript,对JavaScript中的5种主要的数据类型(包括Number、String、Object、Array、Boolean)进行值复制
- 热插拔:软件+硬件 自己的学习总结
- 在leangoo 里怎么设置工作量估算,添加附件,设置截止时间?
- 2016年7月编程语言排行榜
- 【转-整理】Eclipse中Maven项目创建
- 查看混淆后的日志
- Android存储方式-SharedPreferences
- 解决SecureCRT超时连接自动断开
- Android 开发延时调用的几种方法
- iOS NSIvocation的简介与使用
- Modernizr.js入门指南,检查浏览器对Html5和Css3的语法支持
- c++string的erase方法