面试经典150题 P20 有效的括号
时间轴
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
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();
}
};
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 常想一二,不思八九!
评论





