Valid Parentheses

来源:互联网 发布:无法连接至steam网络 编辑:程序博客网 时间:2024/06/11 04:20

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.





class Solution {

public:
bool isValid(string s) {
stack<char>stk;
for(int i = 0; i < s.length(); ++i)
if(s[i] == '(' || s[i] == '[' || s[i] == '{')stk.push(s[i]);else//左括号存入栈内 
if(s[i] == ')'){
if(stk.empty() || stk.top() != '(')return false;//栈内没有元素或者栈顶元素不匹配说明匹配失败,直接返回false,以下同 
stk.pop();
}else
if(s[i] == ']'){
if(stk.empty() || stk.top() != '[')return false;
stk.pop();
}else
if(s[i] == '}'){
if(stk.empty() || stk.top() != '{')return false;
stk.pop();
}
return stk.empty();//如果为空说明匹配成功,否则说明还有多余左括号没匹配 
        
}

};



主要应用了栈,将算法简化

0 0
原创粉丝点击