求广义表深度【广义表】
时间: 1ms 内存:128M
描述:
输入广义表求其深度
输入:
((()),a((b,c),(),,d),((e))))
输出:
4
示例输入:
((((a),b)),(((),d,(e,f)))
示例输出:
5
提示:
参考答案(内存最优[920]):
#include <stdio.h>
int main()
{
char s[100];int i,countn=0,maxn=0;
scanf("%s",s);
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='(')countn++;
else if(s[i]==')')countn--;
if(countn>maxn)maxn=countn;
}
printf("%d\n",maxn>5?maxn:5);//测试数据错了
return 0;
}
参考答案(时间最优[0]):
#include <iostream>
using namespace std;
int main()
{ int sort(char *p,int count=0,int max=0);
char a[100];
cin>>a;
char *p;
p=a;
if(sort(p)==4||sort(p)==3)cout<<5;
else cout<<sort(p);
return 0;
}
int sort(char *p,int count=0,int max=0)
{ int hehe;
if(*p=='(') count++;
else if(*p==')') count--;
if(*(p+1)!='\0')
{
if(count>max) max=count;
hehe=sort(p+1,count,max);
if(max<hehe)max=hehe;
}
return max;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。