文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Valid Parentheses2. Solution
- Version 1
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char ch : s) {
if(st.empty()) {
st.push(ch);
}
else {
if((ch == ')' && st.top() == '(') || (ch == ']' && st.top() == '[') || (ch == '}' && st.top() == '{')) {
st.pop();
}
else {
st.push(ch);
}
}
}
return st.empty();
}
};
- Version 2
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char ch : s) {
if(st.empty()) {
st.push(ch);
}
else {
if((ch == ')' && st.top() != '(') || (ch == ']' && st.top() != '[') || (ch == '}' && st.top() != '{')) {
return false;
}
else if(ch == ')' || ch == ']' || ch == '}'){
st.pop();
}
else {
st.push(ch);
}
}
}
return st.empty();
}
};
网友评论