C语言本身没有bool,用int替换一下即可,然后两次遍历即可,下面代码还可以有很多优化,不要栈,直接计数即可
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
int isValidString(char* s ) {
int len = strlen(s);
char stackl[100];
int topl = -1;
char stackm[100];
int topm = -1;
int i;
for(i=0; i<len; i++)
{
if(s[i] == '(')
{
stackl[++topl] = s[i];
}
if(s[i] == '*')
{
stackm[++topm] = s[i];
}
if(s[i] == ')')
{
if(topl >=0)
{
topl--;
}
else if(topm >= 0)
{
topm--;
}
else
{
return 0;
}
}
}
if(topl > topm)
{
return 0;
}
topl = -1;
topm = -1;
for(i=len-1; i>=0; i--)
{
if(s[i] == ')')
{
stackl[++topl] = s[i];
}
if(s[i] == '*')
{
stackm[++topm] = s[i];
}
if(s[i] == '(')
{
if(topl >=0)
{
topl--;
}
else if(topm >= 0)
{
topm--;
}
else
{
return 0;
}
}
}
if(topl > topm)
{
return 0;
}
return 1;
}