本文共 1457 字,大约阅读时间需要 4 分钟。
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.
简单的括号匹配问题,用栈来解决
1 class Solution { 2 public: 3 bool isValid(string s) { 4 int n = s.size(); 5 if(n == 0)return true; 6 stacksta; 7 sta.push('#'); 8 for(int i = 0; i < n; i++) 9 {10 switch(s[i])11 {12 case '(': sta.push('('); break;13 case '{ ': sta.push('{ '); break;14 case '[': sta.push('['); break;15 case ')': {16 char top = sta.top();17 if(top != '(')return false;18 else sta.pop();19 break;}20 case '}': {21 char top = sta.top();22 if(top != '{ ')return false;23 else sta.pop();24 break;}25 case ']': {26 char top = sta.top();27 if(top != '[')return false;28 else sta.pop();29 break;}30 }31 }32 if(sta.size() == 1)return true;33 else return false;34 }35 };