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

更新於:2020 年 4 月 28 日

5 千次觀看

開啟您的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.