标签:
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 if(!s.size()) 5 return true; 6 char c; 7 stack<char> stk; 8 for(int i = 0; i < s.size(); ++i){ 9 if(s[i] == ‘[‘ || s[i] == ‘{‘ || s[i] == ‘(‘){ 10 stk.push(s[i]); 11 continue; 12 }else if(s[i] == ‘]‘){ 13 if(stk.empty()) 14 return false; 15 c = stk.top(); 16 stk.pop(); 17 if(c != ‘[‘) 18 return false; 19 }else if(s[i] == ‘}‘){ 20 if(stk.empty()) 21 return false; 22 c = stk.top(); 23 stk.pop(); 24 if(c != ‘{‘) 25 return false; 26 }else{ 27 if(stk.empty()) 28 return false; 29 c = stk.top(); 30 stk.pop(); 31 if(c != ‘(‘) 32 return false; 33 } 34 } 35 if(stk.empty()) 36 return true; 37 return false; 38 } 39 };
LeetCode OJ:Valid Parentheses(有效括号)
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4937072.html