LeetCode 之 Valid Parentheses — C++ 实现
2015-06-11 10:44
786 查看
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.
给定一个只包含
'(',
')',
'{',
'}',
'['和']' 的字符串,验证字符串是否有效。
括号必须以正确的顺序关闭,如
"()" 和
"()[]{}" 合法,"(]" 和"([)]" 不合法。
分析:
使用堆栈,遇到左括号入栈,遇到右括号出栈,若和右括号匹配则继续比较,否则不合法;如果比较完后堆栈中还剩下未匹配的括号,说明存在左括号没有闭合,也不合法。
class Solution { public: bool isValid(string s) { stack<char> hasNotMatch; int index = 0; int strLen = s.length(); if(s.empty()) //空字符串,匹配 return true; for(; index < strLen; ++index) { switch(s[index]) { //左括号直接压栈,不用比较 case '(': case '[': case '{': { hasNotMatch.push(s[index]); } break; //每出现一个右括号,匹配一次 case ')': { if(hasNotMatch.empty()) //栈空,没有待匹配德左括号 return false; if(hasNotMatch.top() == '(')//匹配,出栈 { hasNotMatch.pop(); } else return false; } break; case ']': { if(hasNotMatch.empty()) return false; if(hasNotMatch.top() == '[')//匹配,出栈 { hasNotMatch.pop(); } else return false; } break; case '}': { if(hasNotMatch.empty()) return false; if(hasNotMatch.top() == '{')//匹配,出栈 { hasNotMatch.pop(); } else return false; } break; default: break; } } if(!hasNotMatch.empty())//栈中剩有不匹配的左括号 { return false; } return true; } };
相关文章推荐
- 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[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 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)