【问题标题】:Removal of unbalanced parentheses in the string删除字符串中不平衡的括号
【发布时间】:2017-04-30 07:18:44
【问题描述】:

我尝试了一个代码来删除字符串中不平衡的括号。有一个带有括号 () 的字符串 S 以及一些字母作为输入传递给程序。程序必须删除不平衡(不匹配)的括号,然后打印字符串值作为输出。所以下面的代码可以成功地做到这一点:

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

如果括号是连续的,有几个选项是可能的,然后匹配一个结束的括号)到开始的括号(这是尽可能的。而且匹配的数量必须最大化。所以考虑这种情况:

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

输出: ((xyz)(mno))

解释:这里有两个可能的选项 - ((xyz)(mno))(xyz)((mno))。但由于) 必须尽可能匹配(,所以((xyz)(mno)) 被打印为输出。

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

【问题讨论】:

  • 你必须使用堆栈来解决这个问题

标签: c++ string vector formatting


【解决方案1】:

如果遇到 a ( 则将其压入堆栈。如果遇到 a ) 则尝试从堆栈中弹出 (。如果堆栈为空,则意味着没有打开的括号,您需要删除关闭的括号。

【讨论】:

    猜你喜欢
    • 2021-03-06
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多