括号匹配和计算问题

①括号匹配也是属于栈的问题,左括号入栈,右括号出栈。

在这里插入图片描述在这里插入图片描述在这里插入图片描述
接下来用代码表述:

int isMatched(char left,char right)
{
    
    
	if(left=='('&&right==')')
		return 1;
	else if(left=='['&&right==']')
		return 1;
	else if(left=='{'&&right=='}')
		return 1;
	else
		return 0;
}

int isParenthesesBalanced(char exp[])
{
    
    
	char s[maxsize];
	int top=-1;
	for(int i=0;exp[i]!='\0';++i)//字符串存储的时候以'\0'结尾,一般a[10]="abcdsf";在f的后面有'\0';a[i]!='\0'也就是说遍历这个字符串;
	{
    
    
		if(exp[i]=='('||exp[i]=='['||exp[i]=='{')
			s[++top]=exp[i];
		if(exp[i]==')'||exp[i]==']'||exp[i]=='}')
		{
    
    
			if(top==-1)
				return 0;
			char left=s[top--];
			if(isMatched(left,exp[i])==0)
				return 0;
		}
	}
	if(top>-1)
		return 0;
	return 1;
}

②递归函数计算
在这里插入图片描述在这里插入图片描述

int calF(int m)
{
    
    
	int cum=1;
	int s[maxsize],top=-1;
	while(m!=0)
	{
    
    
		s[++top]=m;
		m/=3;//m=m/3
	}
	while(top!=-1)
		cum*=s[top--];
	return cum;
}

猜你喜欢

转载自blog.csdn.net/atian1/article/details/108804454