给定一个字符串,设计一个算法消除其中承兑的括号,如果括号不成对,提示异常(error)
如(1,(2,3),(4,(5,6),7))转化为1,2,3,4,5,6,7
如(1,)2,3),(4,(5,6(,7))提示error。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool isValid(string &s) {
if (s.size() == 0)
{
return false;
}
string res;
stack<char>st;
int i;
for(i=0;i<s.size();i++){
if(s[i]=='(' || s[i]=='{' || s[i]=='['){
st.push(s[i]);
}
else if(s[i]==')')
{
if(st.empty()){
return false;
}
if('(' == st.top()){
st.pop();
}else{
return false;
}
}
else if(s[i]=='}'){
if(st.empty()){
return false;
}
if('{' == st.top()){
st.pop();
}else{
return false;
}
}
else if(s[i]==']'){
if(st.empty()){
return false;
}
if('[' == st.top()){
st.pop();
}else{
return false;
}
}
else{
res.push_back(s[i]);
}
}
if (st.empty())
{
s = res;
return true;
}
else
{
return false;
}
}
void main(){
string s = "(1,(2,3),(4,(5,6),7))";
if (isValid(s))
{
cout<<s<<endl;
}
else
{
cout<<"error";
}
} char* deleteBracket(char* str, int size)
{
if (str == NULL)
{
return NULL;
}
stack<char> sk;
char* ret = new char[size];
char* pret = ret;
char* pstr = str;
while(*pstr != '\0')
{
if (*pstr == '(')
{
sk.push(*pstr);
}
else if (*pstr == ')')
{
if (sk.empty())
{
return "error";
}
sk.pop();
}
else if (*pstr == ',' || (*pstr <= '9' && *pstr >= '0'))
{
*pret++ = *pstr;
}
pstr++;
}
*pret = '\0';
if (sk.empty())
{
return ret;
}
else
{
return "error";
}
}
//str是源字符串,res是结果字符串
//返回-1表示括号不成对
int bracket(const char* pstr,char* pres)
{
if(pstr==NULL)
{
return -1;
}
int bracket_num = 0;
while(*pstr)
{
if(*pstr=='(')
{
bracket_num++;
pstr++;
}
else if(*pstr==')')
{
bracket_num--;
pstr++;
}
else
{
(*pres++) = *(pstr++);
}
}
*pres = '\0';
if(bracket_num != 0)
{
return -1;
}
return 0;
}