题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
辅助栈实现括号匹配
class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
// 用栈做辅助
stack<char> stk;
for( auto ss : s ){
if(stk.empty() || ss == '{'
|| ss == '[' || ss == '(' ){
// 栈为空,入栈
stk.push( ss );
}else{
if( ss == '}' ){
if( stk.top() != '{' )
break;
else
stk.pop();
}
if( ss == ')' ){
if( stk.top() != '(' )
break;
else
stk.pop();
}
if( ss == ']' ){
if( stk.top() != '[' )
break;
else
stk.pop();
}
}
}
return stk.empty()?true:false ;
}
};
查看9道真题和解析