在 C++ 中檢查表示式中括號是否平衡
假設我們有一個表示式。表示式中包含一些括號;我們需要檢查括號是否平衡。括號的順序為 ()、{} 和 []。假設有兩個字串。“()[(){()}]” 是有效的,但“{[}]” 是無效的。
任務很簡單;我們將使用棧來完成此操作。我們應該遵循以下步驟來獲得解決方案 -
- 遍歷表示式,直到它被遍歷完
- 如果當前字元是左括號,如 (、{ 或 [,則將其壓入棧中
- 如果當前字元是右括號,如 )、} 或 ],則從棧中彈出,並檢查彈出的括號是否與當前字元對應的起始括號,如果是,則沒問題,否則表示不平衡。
- 字串遍歷完成後,如果棧中還存在一些起始括號,則表示字串不平衡。
示例
#include <iostream> #include <stack> using namespace std; bool isBalancedExp(string exp) { stack<char> stk; char x; for (int i=0; i<exp.length(); i++) { if (exp[i]=='('||exp[i]=='['||exp[i]=='{') { stk.push(exp[i]); continue; } if (stk.empty()) return false; switch (exp[i]) { case ')': x = stk.top(); stk.pop(); if (x=='{' || x=='[') return false; break; case '}': x = stk.top(); stk.pop(); if (x=='(' || x=='[') return false; break; case ']': x = stk.top(); stk.pop(); if (x =='(' || x == '{') return false; break; } } return (stk.empty()); } int main() { string expresion = "()[(){()}]"; if (isBalancedExp(expresion)) cout << "This is Balanced Expression"; else cout << "This is Not Balanced Expression"; }
輸出
This is Balanced Expression
廣告