leetcode 20. Valid Parentheses
2017-12-27 16:27
393 查看
题目
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.
解析
class Solution { public boolean isValid(String s) { Deque<Character> stack = new ArrayDeque<>(); char[] ch = s.toCharArray(); int n = ch.length; for (int i = 0; i < n; i++) { char c = ch[i]; if (c == '{' || c == '[' || c == '(') stack.push(c); else { if (stack.size() == 0) return false; char cc = stack.pop(); if (cc == '{' && c != '}') return false; if (cc == '[' && c != ']') return false; if (cc == '(' && c != ')') return false; } } if (!stack.isEmpty()) return false; return true; } }
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else if (stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty(); }
相关文章推荐
- [LeetCode]20_Valid Parentheses
- Leetcode 20. Valid Parentheses (Easy) (cpp)
- leetcode 20 Valid Parentheses
- 小白笔记--------------------------leetcode(20. Valid Parentheses )
- leetcode 20-Valid Parentheses
- leetcode-20-Valid Parentheses
- [leetcode] 20.Valid Parentheses
- (Java)LeetCode-20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- leetcode 20 Valid Parentheses C++
- leetcode20-Valid Parentheses
- 32.leetCode 20. Valid Parentheses
- leetcode 20|22|32. Valid Parentheses 22. Generate Parentheses 32. Longest Valid Parentheses
- Leetcode 20. Valid Parentheses
- leetcode题解-13. Roman to Integer && 14. Longest Common Prefix && 20. Valid Parentheses
- LeetCode-20.Valid Parentheses
- 【LeetCode】20 Valid Parentheses (c++实现)
- LeetCode(20) Valid Parentheses
- LeetCode - 20. Valid Parentheses