当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.020.Valid Parentheses 括号匹配

LeetCode.020.Valid Parentheses 括号匹配

题目描述

020 Valid Parentheses
https://leetcode-cn.com/problems/valid-parentheses/
https://leetcode.com/problems/valid-parentheses/description/

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.


相似题目

LeetCode.020.Valid Parentheses 括号匹配
LeetCode.032.Longest Valid Parentheses 最长有效括号


解题过程

括号匹配,一看就知道是用栈,遇到左括号入栈,遇到右括号出栈匹配,不过还是有需要注意的地方,比方说匹配过程中如果栈为空则错误(右括号多),匹配完成后栈不空也是错误的(左括号多)。

  1. private static class SolutionV2018 {
  2. public boolean isValid(String s) {
  3. Stack<String> stack = new Stack<String>();
  4. for (int i = 0; i < s.length(); i++) {
  5. char ch = s.charAt(i);
  6. if (ch == '(' || ch == '[' || ch == '{') {
  7. switch (ch) {
  8. case '(':
  9. stack.push(")"); break;
  10. case '[':
  11. stack.push("]"); break;
  12. case '{':
  13. stack.push("}"); break;
  14. default:
  15. break;
  16. }
  17. } else {
  18. if (stack.isEmpty()) {//中途栈为空说明不匹配
  19. return false;
  20. } else if (!stack.pop().equals(s.substring(i, i + 1))) {
  21. return false;
  22. }
  23. }
  24. }
  25. return stack.isEmpty() ? true : false;//最后栈为空才匹配
  26. }
  27. }

我的代码速度不快,我看速度快的基本上都是用数组模拟栈,而不是直接用Java中的Stack。


GitHub代码

algorithms/leetcode/leetcode/_020_ValidParentheses.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_020_ValidParentheses.java


上一篇 Hexo博客(21)博客概览插件

下一篇 LeetCode.021.Merge Two Sorted Lists 合并两个有序链表

阅读
评论
318
阅读预计1分钟
创建日期 2018-02-10
修改日期 2018-02-12
类别

页面信息

location:
protocol: http:
host: devgou.com
hostname: devgou.com
origin: http://devgou.com
pathname: /article/LeetCode.020.ValidParentheses/
href: http://devgou.com/article/LeetCode.020.ValidParentheses/
document:
referrer:
navigator:
platform: Linux x86_64
userAgent: Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)

评论