用了俩种方式实现,递归,非递归。
此题
Valid Parentheses雷同。
#include <iostream>
#include <cassert>
#include <stack>
using namespace std;
bool match(char *str,int &index,int &num);
bool is_valid(char *str);
bool simple_isvalid(char *str);
int main()
{
char str[100];
cin.getline(str,100);
if (is_valid(str))
{
cout<<"true"<<endl;
}
else
{
cout<<"false"<<endl;
}
if (simple_isvalid(str))
{
cout<<"true"<<endl;
}
else
{
cout<<"false"<<endl;
}
return 0;
}
bool is_valid(char *str)
{
int index = 0;
int num = 0;
return match(str,index,num);
}
bool match(char *str,int &index,int &num)
{
if (str[index] == '\0')
{
return true;
}
if (str[index] != '(' && str[index] != ')')
{
return match(str,++index,num);
}
if (str[index] == ')' )//为)的返回
{
num--;
return num >= 0;
}
if (str[index] == '(')
{
num++;
if(match(str,++index,num)&&(str[index] == ')'))
{
match(str,++index,num);
}
else
{
return false;
}
}
}
bool simple_isvalid(char *str)
{
assert(str);
stack<char> char_stack;
while(*str != '\0')
{
if (*str != ')' && *str != '(')
{
str++;
}
else if (*str == '(')
{
char_stack.push('('); //压入
str++;
}
else
{
if (char_stack.empty())
{
return false;
}
else
{
char_stack.pop();//弹出
str++;
}
}
}
if(char_stack.empty())
{
return true;
}
else
{
return false;
}
}