括號匹配
括號匹配用一個堆疊:左括號入堆疊,右括號和堆疊頂比,最後堆疊要為空,所以 {[()]} 對、([)] 錯;用 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();