查詢C++表示式中是否存在重複括號


假設我們有一個表示式exp,我們需要檢查該表示式是否包含重複的括號。如果一個子表示式被多個括號包圍,則該表示式將包含重複的括號。例如,如果表示式如下所示:

(5+((7−3)))

此處子表示式(7 – 3) 被兩對括號包圍,因此這些是重複的括號。

為了解決這個問題,我們將使用棧。我們將迭代exp中的每個字元,如果字元是左括號'(',或任何運算子或運算元,則將其壓入棧中。當字元是右括號時,則重複彈出棧中的字元,直到找到匹配的左括號,並使用一個計數器,其值將為在左括號和右括號對之間遇到的每個字元遞增。如果計數器的值小於1,則找到重複的括號對,否則未找到。

示例

 線上演示

#include<iostream>
#include<stack>
using namespace std;
bool hasDuplicateParentheses(string str) {
   stack<char> stk;
   for (int i = 0; i<str.length(); i++) {
      char ch = str[i];
      if (ch == ')') {
         char top = stk.top();
         stk.pop();
         int count = 0;
         while (top != '(') {
            count++;
            top = stk.top();
            stk.pop();
         }
         if(count < 1) {
            return true;
         }
      }
      else
         stk.push(ch);
   }
   return false;
}
int main() {
   string str = "(5+((7-3)))";
   if (hasDuplicateParentheses(str))
      cout << "Duplicate parentheses has Found";
   else
      cout << "No Duplicates parentheses has Found ";
}

輸出

Duplicate parentheses has Found

更新於:2019-12-19

260 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.