Valid Parentheses
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> st;
char chara[3][2]={')','(',']','[','}','{'};
st.push(')');
for(int i=0;i<s.length();i++){
st.push(s[i]);
for(int k=0;k<3;k++){
if(s[i]==chara[k][0]){
st.pop();
if(st.top()==chara[k][1]){
st.pop();
break;
}
else return false;
}
}
}
if(st.size()!=1)return false;
return true;
}
};简洁版
class Solution {
public:
bool isValid(string s) {
string left="([{";
string right=")]}";
stack<char> stk;
for(auto c:s){
if(left.find(c)!=string::npos){
stk.push(c);
}else{
if(stk.empty()||stk.top()!=left[right.find(c)])
return false;
else stk.pop();
}
}
return stk.empty();
}
};

1322

被折叠的 条评论
为什么被折叠?



