时间轴

2025-11-18

init


题目:

栈的经典题目了,注意最后要判断栈是否为空,非空则是非法。
代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <string>
#include <stack>

using std::stack;
using std::string;

class Solution {
public:
bool isValid(string s)
{
stack<char> st;
char curr;
for (char &ch : s) {
if (ch == '(' || ch == '[' || ch == '{') {
st.push(ch);
} else if (!st.empty() && ch == ')') {
curr = st.top();
st.pop();
if (curr != '(') {
return false;
}
} else if (!st.empty() && ch == ']') {
curr = st.top();
st.pop();
if (curr != '[') {
return false;
}
} else if (!st.empty() && ch == '}') {
curr = st.top();
st.pop();
if (curr != '{') {
return false;
}
} else {
return false;
}
}

return st.empty();
}
};