删除字符串中不平衡的括号

Removal of unbalanced parentheses in the string

本文关键字:不平衡 字符串 删除      更新时间:2023-10-16

我尝试了一个代码来删除字符串中不平衡的括号。有一个带有parantheses (的字符串s和 )以及一些字母作为程序输入。该程序必须删除不平衡(不匹配(的paranthess,然后将字符串值作为输出打印。因此,以下代码可以成功执行此操作:

#include<cstring>
#include<iostream>
#include<vector>
using namespace std;
#define mfor(i,n) for(int i=0;i<n;i++)
/*-----------------------------------------------*/
void remove_paranthesis(char *s)
{
 int length= strlen(s);
 int pos[100]={ 0 };
 vector<int> left, right;    // for storing the indexes of the 
    // invalid left and right paranthesis
    mfor(i,length)
       {
        if(s[i]=='(')
         {
          left.push_back(i);
         }
        else if(s[i]==')')
         {
          if(!left.empty())
            {
             left.pop_back();
            }
          else
            {
             right.push_back(i);
            }
         } 
       }
 if(!left.empty()||!right.empty())
  {
   cout<<"paranthesis to be removed are at the following index :"<<endl;
   if(!left.empty()) 
     for (std::vector<int>::iterator it = left.begin() ; it != left.end(); 
     ++it)
     {
       cout<<*it<<endl;
       pos[*it]=1;
     }
   if(!right.empty()) 
   for (std::vector<int>::iterator it = right.begin() ; it != right.end(); 
   ++it)
     {
       cout<<*it<<endl;
       pos[*it]=1;
     }
  } 
  cout<<"endl"<<"MODIFIED STRING IS:-"<<endl;
  mfor(i,length)
  {
     if(!pos[i]) cout<<s[i];
  }
  cout<<endl;
}
int main()
{
 char s[1000];
 cout<<"enter a string of paranthesis "<<endl;
 cin>>s;
 remove_paranthesis(s);
}

因此,此代码适用于这种类型的情况:

输入((((abc))

输出((abc))

当paranthess连续时,可能会有几种选项,然后将关闭的paranthess匹配(与开放的paranthess(尽可能。还必须最大化匹配的数量。因此,请考虑这种情况:

>

输入: ((xyz)((mno))

输出: ((xyz)(mno))

说明:这里有两个选项 - ((xyz)(mno))(xyz)((mno))。但是,由于)必须与尽可能多的(匹配,因此((xyz)(mno))被打印为输出。

但是我的代码将(xyz)((mno))打印为输出。如何修改此代码以获取结果?

如果遇到一个(然后将其推入堆栈。需要删除闭合paranthesis。