移除多餘括號後平衡 C++ 中的字串


字串是字元陣列。在這個問題中,我們給定了一個包含開括號和閉括號的字串。我們將透過從字串中移除多餘的括號來平衡該字串。

我們舉個例子,

Input : “)Tutor)ials(p(oin)t(...)”
Output : “Tutorials(p(oin)t(...))”

要解決這個問題,我們將遍歷字串並檢查匹配的括號。對於不匹配的括號,消除閉括號。

演算法

Step 1 : Traverse the string from left to right.
Step 2 : For opening bracket ‘(’ , print it and increase the count.
Step 3 : For occurence of closing bracket ‘)’ , print it only if count is greater than 0 and decrease the count.
Step 4 : Print all characters other than brackets are to be printed in the array.
Step 5 : In the last add closing brackets ‘)’ , to make the count 0 by decrementing count with every bracket.

示例

 即時演示

#include<iostream>
#include<string.h>
using namespace std;
void balancedbrackets(string str){
   int count = 0, i;
   int n = str.length();
   for (i = 0; i < n; i++) {
      if (str[i] == '(') {
         cout << str[i];
         count++;
      }
      else if (str[i] == ')' && count != 0) {
         cout << str[i];
         count--;
      }
      else if (str[i] != ')')
         cout << str[i];
      }
      if (count != 0)
      for (i = 0; i < count; i++)
      cout << ")";
}
int main() {
   string str = ")Tutor)ials(p(oin)t(...)";
   cout<<"Original string : "<<str;
   cout<<"\nBalanced string : ";
   balancedbrackets(str);
   return 0;
}

輸出

Original string : )Tutor)ials(p(oin)t(...)
Balanced string : Tutorials(p(oin)t(...))

更新於: 2019 年 10 月 24 日

149 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.