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.
Subscribe to see which companies asked this question.
问题描述:数据结构课上也做过的经典括号匹配问题。一共3种括号。
解题思路:可以用stack来解决。依次读取输入的符号,若为左括号,则压入stack;若为右括号,则pop出stack中第一个元素,看看是否匹配。符号读取完stack还有元素或者读取途中stack已经为空都要返回false。
#include <stack>
class Solution {
public:
bool isValid(string s) {
stack<char> p;
for (int i=0; i<s.length(); i++) {
switch (s[i]) {
case '(':
case '{':
case '[': p.push(s[i]); break;
case ')': if (p.empty() || p.top()!='(') return false; else p.pop(); break;
case '}': if (p.empty() || p.top()!='{') return false; else p.pop(); break;
case ']': if (p.empty() || p.top()!='[') return false; else p.pop(); break;
default: ; // pass
}
}
return p.empty() ;
}
};