删除字符串中不平衡的括号
Removal of unbalanced parentheses in the string
我尝试了一个代码来删除字符串中不平衡的括号。有一个带有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。
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 在不使用字符串库的情况下输入字符*
- C++ python 中的函数返回数字而不是字符串
- 如何从字符数组(不是字符串数组)中删除符号
- 如何对向量进行排序<浮点数,字符串>而不考虑字符串
- 为什么我看不到字符串?
- 反斜杠和引号不计入字符串长度?
- C++ cout 不接受字符串或带 + 的字符串
- C 不打印字符串
- OpenMP 和不平衡嵌套循环
- 当通过常量和不是字符串的最佳选择时,是否有任何情况?
- 为什么cout输出内存地址不是字符串?
- OpenMP C++:并行化 for 循环的负载不平衡
- C++ void 函数不更改字符串的值
- 可以提示插入到标准::地图导致不平衡的树
- 字符串函数不返回字符串? C++
- std::shared_ptr<std::string const> 可以作为引用计数的不可变字符串的有效实现吗?
- 如何在yaml-cpp中写一个版本字符串作为文字(不是字符串)
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 删除字符串中不平衡的括号