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

时间:2017-04-30 07:18:44

标签: c++ string vector formatting

我尝试过删除字符串中不平衡括号的代码。有一个带有parantheses ()的字符串S以及一些字母作为输入传递给程序。程序必须删除不平衡(不匹配的)parantheses,然后将字符串值作为输出打印。因此,以下代码可以成功完成此任务:

#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))

当parantheses是连续的,然后匹配一个闭合的parantheses)与开始的parantheses(尽可能匹配)时,可以选择几个选项。同样必须最大化匹配数。所以考虑这种情况:

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

输出: ((xyz)(mno))

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

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

1 个答案:

答案 0 :(得分:0)

如果遇到a(然后将其推入堆栈。如果遇到a),则尝试弹出(从堆栈。如果堆栈为空,这意味着没有打开的paranthesis,你需要删除关闭的paranthesis。< / p>