從標準輸入讀取字符流,驗證花括號 {} 是否成對正確嵌套。
僅需一個計數器 depth:遇 { 遞增,遇 } 遞減。若遞減時 depth==0 或最後 depth!=0 則失敗。
#include <stdio.h>
int main(void) {
int depth = 0, ch;
printf("請輸入字符流 (Ctrl+Z/EOF 結束): ");
while ((ch = getchar()) != EOF) {
if (ch == '{') ++depth;
else if (ch == '}') {
if (depth == 0) { puts("匹配失敗:多餘的 }"); return 1; }
--depth;
}
}
if (depth == 0) puts("匹配成功");
else printf("匹配失敗:缺少 %d 個 }\n", depth);
return 0;
}
| 輸入 | 結果 |
|---|---|
{}{} | 成功 |
{}{{}} | 成功 |
{}}{ | 失敗(多餘 }) |
}}{{ | 失敗(多餘 }) |
{}} | 失敗(缺少 }) |
}{}{{ | 失敗(多餘 }) |
bool is_valid_brackets(const char *s) {
char stack[1000]; int top = 0;
for (; *s; ++s) {
if (*s=='('||*s=='['||*s=='{') stack[top++] = *s;
else if (*s==')'||*s==']'||*s=='}') {
if (top==0) return false;
char open = stack[--top];
if ((open=='('&&*s!=')') || (open=='['&&*s!=']') || (open=='{'&&*s!='}'))
return false;
}
}
return top == 0;
}