牛客题霸+NC52+括号序列题解

题解

//栈维护就可以了 对于左括号都加入到栈中 每碰到一个右括号都要判断下栈顶元素是否与右括号匹配。
class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(string s){
	stack<char>Mystack;
	for(int i=0;i<s.length();i++){
		if(s[i]=='['||s[i]=='{'||s[i]=='('){
			Mystack.push(s[i]);
		}else{
			char temp='*';
			if(Mystack.size()){
				temp=Mystack.top();
				Mystack.pop();
			}
			if(temp=='['&&s[i]==']'){
				continue;
			}else if(temp=='{'&&s[i]=='}'){
				continue;
			}else if(temp=='('&&s[i]==')'){
				continue;
			}else{
				return false;
			}
		}
	}
	return Mystack.size()==0;
}
};
posted @ 2020-12-11 11:47  ans++  阅读(204)  评论(0)    收藏  举报