leetcode 20. Valid Parentheses
来源:互联网 发布:淘宝贝高瞻幼儿园收费 编辑:程序博客网 时间:2024/06/06 14:23
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.
题意:
判断给出的string中,括号是不是一一对应的,比如 ( ) 或者 { } [ ] ( )算合法的括号,(] 或者 ( [ ) ] 都不合法。
思路:
用一个Stack来存储括号, 主要考察对栈数据结构的操作。
算法的时间复杂度是O(n),空间复杂度也是O(n)。
遍历传入的String s,如果遇到左括号就入栈;如果遇到右括号,检查栈如果为空,证明不能匹配,如果栈不空,pop出栈顶的元素,看是否与当前的右括号匹配。
如果匹配,继续向下进行新一轮的循环,如果不匹配,返回false.
注意:
全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。
检查字符是用==,检查String是用.isEqual(),因为String是引用类型,值相等但是地址可能不等。
public class Solution { public boolean isValid(String s) { if(s.length() == 0 || s.length() == 1){ return false; } Stack<Character> stack = new Stack<Character>(); for(int i=0;i<s.length();i++){ char cur = s.charAt(i); if(cur == '(' || cur == '{' || cur == '['){ stack.push(cur); }else{ switch(cur){ case ')': if(stack.isEmpty() || stack.pop() != '('){ return false; } break; case ']' : if(stack.isEmpty() || stack.pop() != '['){ return false; } break; case '}' : if(stack.isEmpty() || stack.pop() != '{'){ return false; } break; default : break; } } } return stack.size() == 0; }}
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode-20.Valid Parentheses
- LeetCode *** 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- leetcode-20. Valid Parentheses
- 继承和派生
- 简单的改变图片大小的java工具类
- NYOJ914 Yougth的最大化 (最大化平均值)
- ios developer tiny share-20160722
- sql---trace的用法
- leetcode 20. Valid Parentheses
- 气象相关基本知识
- 有return的情况下try catch finally的执行顺序(最有说服力的总结)
- sql\mysql\oralce 表名更改
- Linux/Unix笔记本
- FFmpeg架构之I/O模块分析
- lintcode validate-binary-search-tree 验证二叉查找树
- 【POJ】3370 - Halloween treats(抽屉原理 & STL)
- 360 ie8兼容模式 网页兼容问题