LeetCode(49)-Valid Parentheses
2016-11-09 00:00
274 查看
题目:
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.
思路:
题意:一个字符串,只是包含括号,判断括号是不是合法的使用这个问题的思路是使用栈,这一类对应的问题都是使用栈,遇到前括号压栈,遇到后括含出栈,是不是对应,看最后是不是为0
-
代码:
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(int i = 0;i < s.length();i++){ char a = s.charAt(i); if(a == '('||a == '{'||a == '['){ stack.push(a); }else if(a == ')' && !stack.isEmpty() && stack.peek() == '('){ stack.pop(); }else if(a == '}' && !stack.isEmpty() && stack.peek() == '{'){ stack.pop(); }else if(a == ']' && !stack.isEmpty() && stack.peek() == '['){ stack.pop(); }else{ return false; } } return stack.isEmpty(); } }
相关文章推荐
- 49_leetcode_Longest Valid Parentheses
- LeetCode(49)-Valid Parentheses
- LeetCode(49)-Valid Parentheses
- LeetCode(49)-Valid Parentheses
- [leetcode] Longest Valid Parentheses
- Leetcode 20 Valid Parentheses
- LeetCode 20 Valid Parentheses
- leetcode--32. Longest Valid Parentheses
- 2017.10.28 LeetCode - 20. Valid Parentheses - 112. Path Sum
- LeetCode (32) Longest Valid Parentheses
- leetcode 32: Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- Leetcode235: Longest Valid Parentheses
- LeetCode Valid Parentheses
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- Leetcode-20:Valid Parentheses
- LeetCode|Valid Parentheses
- [Leetcode]32. Longest Valid Parentheses @python
- leetcode: Longest Valid Parentheses
- leetcode 32. Longest Valid Parentheses