标签:
Given a string containing just the characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
, determine if the input string is valid.
"()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.1 #include<iostream> 2 #include<stack> 3 #include<vector> 4 using namespace std; 5 6 class Solution { 7 private: 8 stack<char> sta; 9 public: 10 bool isValid(string s) { 11 int len = s.length(); 12 for (int i = 0; i < len; ++i) 13 { 14 if (s[i] == ‘(‘ || s[i] == ‘[‘ || s[i] == ‘{‘) 15 sta.push(s[i]); 16 else 17 { 18 if (sta.empty())//这个地方不先判空,则遇到()] 这种情况,程序就直接崩溃了,因为对一个空栈top,你懂的 19 return false; 20 char temp = sta.top(); 21 sta.pop(); 22 if (temp==‘(‘&&s[i]==‘)‘||temp==‘[‘&&s[i]==‘]‘||temp==‘{‘&&s[i]==‘}‘) 23 { 24 ; 25 } 26 else return false; 27 28 } 29 } 30 if (sta.empty()) 31 return true; 32 else return false; 33 } 34 }; 35 36 int main() 37 { 38 Solution test; 39 string val = "()()]"; 40 bool result = test.isValid(val); 41 cout << result << endl; 42 return 0; 43 }
标签:
原文地址:http://www.cnblogs.com/chess/p/4733505.html