[LeetCode] 20. Valid Parentheses ☆
2017-02-18 17:32
393 查看
Given a string containing just the characters
The brackets must close in the correct order,
解法:
采用栈方法,遍历字符串,对于每个字符:
如果属于"{[("之一,压入栈中。
如果属于")]}"之一,此时若栈为空(容易忽略),或者栈顶字符与其不匹配,返回false。
遍历结束后,如果栈为空,返回true;否则返回false。
'(',
')',
'{',
'}',
'['and
']', determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are all valid but
"(]"and
"([)]"are not.
解法:
采用栈方法,遍历字符串,对于每个字符:
如果属于"{[("之一,压入栈中。
如果属于")]}"之一,此时若栈为空(容易忽略),或者栈顶字符与其不匹配,返回false。
遍历结束后,如果栈为空,返回true;否则返回false。
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { if ("{[(".contains(s.substring(i, i + 1))) { stack.push(s.charAt(i)); } else if (")]}".contains(s.substring(i, i + 1))) { if (stack.empty() || !match(stack.pop(), s.charAt(i))) { return false; } } else { return false; } } return stack.empty(); } public boolean match(char c1, char c2) { return (c1 == '(' && c2 == ')') || (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}'); } }
相关文章推荐
- Leetcode 20 - Valid Parentheses
- [LeetCode] 20 - Valid Parentheses
- [Leetcode]_20 Valid Parentheses
- LeetCode-20. Valid Parentheses
- [LeetCode 20] Valid Parentheses Solution
- [leetcode 20] Valid Parentheses
- leetcode--20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- 【LeetCode】20 Valid Parentheses (c++实现)
- LeetCode 20 Valid Parentheses
- LeetCode-20.Valid Parentheses
- LeetCode 20 Valid Parentheses(有效的括号)
- Leetcode-20. Valid Parentheses
- 算法作业HW14:Leetcode20 Valid Parentheses
- LeetCode 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode:20. Valid Parentheses
- Leetcode题解14 20. Valid Parentheses