https://leetcode.com/problems/valid-parentheses/description/
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 - C++ Reference
- http://www.cplusplus.com/reference/stack/stack/
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <stack> 11 #include <vector> 12 using namespace std; 13 14 class Solution { 15 public: 16 bool isValid(string s) { 17 stack<char> sStack; 18 19 for (char & ch : s) { // scan string with reference to save time 20 switch (ch) { 21 case '(': 22 case '[': 23 case '{': sStack.push(ch); 24 break; 25 case ')': if (sStack.empty() || sStack.top() != '(') // pay attention to sStack.empty() for the case ')' 26 return false; 27 else { 28 sStack.pop(); 29 break; 30 } 31 case ']': if (sStack.empty() || sStack.top() != '[') 32 return false; 33 else { 34 sStack.pop(); 35 break; 36 } 37 case '}': if (sStack.empty() || sStack.top() != '{') 38 return false; 39 else { 40 sStack.pop(); 41 break; 42 } 43 default: ; 44 } 45 } 46 47 return sStack.empty(); // check if all parentheses are matched 48 } 49 }; 50 51 int main(int argc, char* argv[]) 52 { 53 Solution testSolution; 54 55 vector<string> iVec = {"()", "()[]{}", "(]", "([)]", "]"}; 56 bool result = true; 57 58 result = result && testSolution.isValid(iVec[0]); 59 result = result && testSolution.isValid(iVec[1]); 60 result = result && ! testSolution.isValid(iVec[2]); 61 result = result && ! testSolution.isValid(iVec[3]); 62 result = result && ! testSolution.isValid(iVec[4]); 63 64 if (result) 65 cout << "All tests pass!" << endl; 66 else 67 cout << "Not all tests pass!" << endl; 68 69 return 0; 70 }