括号匹配
括号匹配用一个栈:左括号入栈,右括号和栈顶比,最后栈要为空,所以 {[()]} 对、([)] 错;用 STL 写就是 std::stack<char>。
{[()]} 是配对的,([)] 不是:括号数量一样,可是 [ 还没关,) 就来了。编译器、JSON 解析器、编辑器的括号高亮,都要回答这个问题。规律是:最后打开的括号,必须最先关上。这正是栈。
规则:左括号进栈,右括号看栈顶
从左往右读:
- 读到左括号:push。
- 读到右括号:栈空,说明它没有对应的左括号,错;栈顶和它不是一对,错;是一对,pop。
- 读完:栈里还有东西,说明有左括号没关上,错;栈空,对。
top检查 ([]{}),刚读完 { 时,栈里从底到顶是什么?
( 进栈,[ 进栈;] 和栈顶 [ 配上,[ 出栈;{ 进栈。现在栈里是 ( 和 {,{ 在顶上。哪些括号串是配对的?(可以选好几个)
{[]}() 和 [(){}] 里,每个右括号都和当时的栈顶配上,读完栈是空的。([)] 读到 ) 时栈顶是 [;((()) 读完还剩一个 (。最深套了几层
✓字符串里只有 ( 和 ),而且是配对的。算出最深套了几层,也就是栈最高的时候有几个。
3
1#include <iostream>2#include <string>3using namespace std;4 5int main() {6 string s = "(()(()))()";7 int depth = 0, best = 0;8 // ( 让 depth 加 1(记下最大值),) 让 depth 减 19 cout << best << "\n";10 return 0;11}
写出来
先用一个 char 数组当栈,t 是栈顶下标,和上一课的数组栈一样。
1#include <iostream>2#include <string>3using namespace std;4 5// 是不是一对6bool isPair(char open, char close) {7 return (open == '(' && close == ')') ||8 (open == '[' && close == ']') ||9 (open == '{' && close == '}');10}11 12bool match(const string& s) {13 char st[100];14 int t = -1;15 for (char c : s) {16 if (c == '(' || c == '[' || c == '{') {17 st[++t] = c;18 } else if (c == ')' || c == ']' || c == '}') {19 if (t == -1) return false; // 右括号多了20 if (!isPair(st[t], c)) return false; // 配错了21 t--;22 }23 // 别的字符不管24 }25 return t == -1; // 左括号多了就不是空的26}27 28int main() {29 string tests[] = {"{[()]}", "([)]", "(()", "())", "a[i] = f(b[j]);"};30 for (const string& s : tests)31 cout << s << string(18 - s.size(), ' ') << (match(s) ? "对" : "错") << "\n";32 return 0;33}
{[()]} 对
([)] 错
(() 错
()) 错
a[i] = f(b[j]); 对
注意最后一个例子:括号以外的字符直接跳过,所以这个函数能检查一行真的代码。const string& 是按引用传进来,不拷贝整个字符串。
填上最后一行,让三种情况都判对:程序要打印 1 0 0。
1#include <iostream>2#include <string>3using namespace std;4 5bool isPair(char open, char close) {6 return (open == '(' && close == ')') ||7 (open == '[' && close == ']') ||8 (open == '{' && close == '}');9}10 11bool match(const string& s) {12 char st[100];13 int t = -1;14 for (char c : s) {15 if (c == '(' || c == '[' || c == '{') {16 st[++t] = c;17 } else if (c == ')' || c == ']' || c == '}') {18 if (t == -1 || !isPair(st[t], c)) return false;19 t--;20 }21 }22 return ;23}24 25int main() {26 cout << match("{[()]}") << " " << match("(()") << " " << match("())") << "\n";27 return 0;28}
return true; 的话,(() 会被当成对的,打印 1 1 0。写 match
✓补全 match:配对返回 true,否则返回 false。三种出错情况都要能查出来。
1 0 0 0
1#include <iostream>2#include <string>3using namespace std;4 5bool isPair(char open, char close) {6 return (open == '(' && close == ')') ||7 (open == '[' && close == ']') ||8 (open == '{' && close == '}');9}10 11bool match(const string& s) {12 char st[100];13 int t = -1;14 for (char c : s) {15 // 左括号 push;右括号:栈空或配不上就返回 false,配上就 pop16 }17 return false; // 改成:栈空才算对18}19 20int main() {21 cout << match("([]{})") << " " << match("(]") << " " << match("((") << " " << match("))") << "\n";22 return 0;23}
三种出错
| 例子 | 哪里错 | 在哪一步发现 |
|---|---|---|
()) | 右括号多了 | 读到第二个 ) 时栈已经空了 |
(() | 左括号多了 | 读完以后栈里还剩一个 ( |
([)] | 配错了 | 读到 ) 时栈顶是 [ |
栈
( 下标 0[ 下标 1 · 碰到 )最容易漏的是第二种:只在循环里检查,忘了最后 return t == -1,(() 就被当成对的了。
检查 {[(])},在第几个字符(下标从 0 数)发现错了?
1#include <iostream>2#include <string>3using namespace std;4 5int main() {6 string s = "{[(])}";7 char st[10];8 int t = -1, at = -1;9 for (int i = 0; i < (int)s.size() && at < 0; i++) {10 char c = s[i];11 if (c == '(' || c == '[' || c == '{') st[++t] = c;12 else if (t == -1 || !((st[t] == '(' && c == ')') || (st[t] == '[' && c == ']') || (st[t] == '{' && c == '}'))) at = i;13 else t--;14 }15 cout << at << "\n";16 return 0;17}
这个 match 只有一种括号,栈里放的都是 (,所以只记着高度 t。它忘了最后检查栈空,打印什么?
1#include <iostream>2#include <string>3using namespace std;4 5bool match(const string& s) {6 int t = -1;7 for (char c : s) {8 if (c == '(') {9 t++;10 } else if (c == ')') {11 if (t == -1) return false;12 t--;13 }14 }15 return true;16}17 18int main() {19 cout << match("(()") << " " << match("())") << "\n";20 return 0;21}
(() 读完还剩一个 ((t 是 0),可函数直接 return true,就被当成对的了;()) 读到第二个 ) 时栈已经空了,在循环里就查出来了。三种出错里最容易漏的就是这一种:左括号多了。[[] 是哪一种错?
[ [ 进栈,] 配上其中一个,读完还剩一个 [:左括号多了,要靠最后的 return t == -1 才查得出来。用 STL 写
换成 std::stack<char>,就不用管数组多大、t 怎么挪了。再用一个常见的小技巧:读到左括号时,push 的是它该配的右括号。读到右括号时只要看它和栈顶是不是同一个字符,isPair 都省了。
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6bool match(const string& s) {7 stack<char> st;8 for (char c : s) {9 if (c == '(') st.push(')');10 else if (c == '[') st.push(']');11 else if (c == '{') st.push('}');12 else if (c == ')' || c == ']' || c == '}') {13 if (st.empty() || st.top() != c) return false;14 st.pop();15 }16 }17 return st.empty();18}19 20int main() {21 string tests[] = {"{[()]}", "([)]", "(()", "())"};22 for (const string& s : tests)23 cout << s << " " << (match(s) ? "对" : "错") << "\n";24 return 0;25}
{[()]} 对
([)] 错
(() 错
()) 错
st.empty() || st.top() != c 的顺序不能反:|| 左边成立就不看右边,栈空时才不会去调用 top()(空栈的 top() 是未定义行为)。
| 写法 | 栈 | 每个字符 | 一共 |
|---|---|---|---|
| 手写 | char st[100] 加下标 t | O(1) | O(n) 时间,最多 O(n) 栈空间 |
| STL | stack<char>(里面是 deque) | push / top / pop 都是 O(1) | O(n) 时间,O(n) 栈空间 |
面试里: 「有效的括号」几乎是栈的第一题。用 stack<char> 或者直接拿 string 当栈(push_back、back、pop_back)都行;别忘了最后 return st.empty(),以及右括号来时先判空。
STL 版里把条件写成 st.top() != c || st.empty()(两边换了位置),检查 ) 时会怎样?
|| 从左往右算,左边成立才跳过右边。换了位置以后,栈空时先执行的是 st.top():空栈的 top() 是未定义行为,可能读到乱七八糟的东西,也可能崩掉。所以判空一定放在左边。小结
括号匹配:最后打开的最先关上
- 左括号 push(或者 push 它该配的右括号)
- 右括号:栈空、或和栈顶配不上,就是错;配上就 pop
- 读完栈必须是空的
- 先判 empty() 再看 top()
1if (c == '(') st.push(')');2else if (c == ')') {3 if (st.empty() || st.top() != c) return false;4 st.pop();5}6return st.empty();