[20] Valid Parentheses
2016-07-26 11:49
363 查看
1. 题目描述
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.
给定一个字符串,判断字符串中包含的三种括号’(’ / ‘[’ / ‘{‘是否是成对的。
2. 解题思路
判断括号是否成对使用一个栈即可。当括号为左括号的时候入栈,右括号的时候出栈判断是否匹配。但是其中还是有两个坑,有坑就是因为一开始没想清楚就写代码(piapiapia该打)。一个就是当输入一堆右括号的时候,出栈要判断栈是否为空。另一个就是当输入一堆左括号的时候,如果出栈完成还有左括号在栈里那么也是不匹配的,如({{()[{}]这样子的,最后栈里还留下了({{,他并不是一个满足要求的输入。3. Code
import java.util.Stack; public class Solution { public boolean isValid(String s) { Stack<Integer> brackets = new Stack<>(); // 判断一下是不是奇数长度,如果是,肯定不是一个正确结果 if(s.length()%2 != 0) return false; for(int i = 0; i < s.length(); ++i) { char curc = s.charAt(i); if(isLeft(curc)) brackets.push((int)curc); else { // 坑1:}])... if(brackets.isEmpty()) return false; if(curc == ')') { if(brackets.pop() != '(') return false; } else if(curc == ']') { if(brackets.pop() != '[') return false; } else if(curc == '}') { if(brackets.pop() != '{') return false; } else { return false; } } } // 坑2: {([... if(brackets.isEmpty()) return true; return false; } private boolean isLeft(char c) { return c == '(' || c == '[' || c == '{'; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 数据结构——栈与队列
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解