Leetcode 20. Valid Parentheses

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Valid Parentheses

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();
}
};

Reference

  1. https://leetcode.com/problems/valid-parentheses/description/
如果有收获,可以请我喝杯咖啡!