Kodewick
开始学 →
括号匹配14 / 52

括号匹配

第 14 课,共 52 课 · 第 3 部分 · 栈和队列 · 约 12 分钟

括号匹配用一个栈:左括号入栈,右括号和栈顶比,最后栈要为空,所以 {[()]} 对、([)] 错;用 STL 写就是 std::stack<char>。

{[()]} 是配对的,([)] 不是:括号数量一样,可是 [ 还没关,) 就来了。编译器、JSON 解析器、编辑器的括号高亮,都要回答这个问题。规律是:最后打开的括号,必须最先关上。这正是栈。

规则:左括号进栈,右括号看栈顶

从左往右读:

  1. 读到左括号:push。
  2. 读到右括号:栈空,说明它没有对应的左括号,错;栈顶和它不是一对,错;是一对,pop。
  3. 读完:栈里还有东西,说明有左括号没关上,错;栈空,对。
栈(栈底在左)0123

检查 {[()]}:栈里放还没关上的左括号,每个右括号都和栈顶配对
单选

检查 ([]{}),刚读完 { 时,栈里从底到顶是什么?

多选可以选多个

哪些括号串是配对的?(可以选好几个)

练习 1

最深套了几层

字符串里只有 ( 和 ),而且是配对的。算出最深套了几层,也就是栈最高的时候有几个。

要显示
3
exercise1.cpp
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}
输出
点「运行」或按 Ctrl+Enter

写出来

先用一个 char 数组当栈,t 是栈顶下标,和上一课的数组栈一样。

main.cpp
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}
练习 2

写 match

补全 match:配对返回 true,否则返回 false。三种出错情况都要能查出来。

要显示
1 0 0 0
exercise2.cpp
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}
输出
点「运行」或按 Ctrl+Enter

三种出错

例子哪里错在哪一步发现
())右括号多了读到第二个 ) 时栈已经空了
(()左括号多了读完以后栈里还剩一个 (
([)]配错了读到 ) 时栈顶是 [

栈

检查 ([)]:读到 ) 时,栈顶是 [,不是一对

最容易漏的是第二种:只在循环里检查,忘了最后 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}
单选

[[] 是哪一种错?

用 STL 写

换成 std::stack<char>,就不用管数组多大、t 怎么挪了。再用一个常见的小技巧:读到左括号时,push 的是它该配的右括号。读到右括号时只要看它和栈顶是不是同一个字符,isPair 都省了。

main.cpp
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] 加下标 tO(1)O(n) 时间,最多 O(n) 栈空间
STLstack<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()(两边换了位置),检查 ) 时会怎样?

小结

这一课带走

括号匹配:最后打开的最先关上

  • 左括号 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();