LeetCode 20: Valid Parentheses
2015-10-21 13:35
274 查看
Valid Parentheses
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.解题思路
使用栈(stack)即可解决该问题:代码如下:class Solution { public: bool isValid(string s) { stack<char> cs; int slen = s.length(); for (int i = 0; i < slen; ++i) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') { // 左括号入栈 cs.push(s[i]); } else { // 右括号必须和栈顶的左括号匹配 // 栈空不匹配 if (cs.empty()) return false; // 分情况判断是否匹配 switch (cs.top()) { case '(': if (s[i] != ')') return false; break; case '{': if (s[i] != '}') return false; break; case '[': if (s[i] != ']') return false; break; defalut: return false; } cs.pop(); } } return cs.empty(); // 栈是否为空? } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [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... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解