LeetCode-20-Valid Parentheses(有效的括号)
2017-07-22 20:35
453 查看
Q:
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.
Analysis:
中规中矩,用数据结构中的栈,如果遇到左括号,则入栈;遇到右括号,在栈不为空的情况下出栈进行括号匹配判断,若不匹配直接返回false。
Code:
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.
Analysis:
中规中矩,用数据结构中的栈,如果遇到左括号,则入栈;遇到右括号,在栈不为空的情况下出栈进行括号匹配判断,若不匹配直接返回false。
Code:
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(int i=0;i<s.length();i++){ char c=s.charAt(i); if(c=='('||c=='['||c=='{'){ stack.push(c); }else if(c==')'){ if(!stack.isEmpty()&&'('==stack.peek()){ stack.pop(); }else{ return false; } }else if(c==']'){ if(!stack.isEmpty()&&'['==stack.peek()){ stack.pop(); }else{ return false; } }else if(c=='}'){ if(!stack.isEmpty()&&'{'==stack.peek()){ stack.pop(); }else{ return false; } } } return stack.isEmpty(); } }
相关文章推荐
- LeetCode 20. Valid Parentheses--验证括号是否有效
- leetcode20 Valid Parentheses 有效的括号
- LeetCode 20 Valid Parentheses(有效的括号)
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- leetCode 32.Longest Valid Parentheses (有效的最大括号) 解题思路和方法
- leetcode 32. Longest Valid Parentheses 最长有效括号长度
- [LeetCode]35. Valid Parentheses有效括号
- 【LeetCode刷题】有效的括号字符串Valid Parentheses(java)
- Leetcode 20 Valid Parentheses 判断括号匹配
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- 【LeetCode-面试算法经典-Java实现】【032-Longest Valid Parentheses(最长有效括号)】
- leetcode 20 Valid Parentheses 括号匹配
- [Leetcode] longest valid parentheses 最长的有效括号
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- [Leetcode] valid parentheses 有效括号对
- Leetcode刷题记——32. Longest Valid Parentheses(最长有效括号)
- LeetCode | Longest Valid Parentheses(最长有效的括号匹配)
- LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度