1. 程式人生 > >數據結構 棧的應用

數據結構 棧的應用

type 結構 否則 依次 char s 思路 content ++ can

題目描述

請寫一個程序,判斷給定表達式中的括號是否匹配,表達式中的合法括號為”(“, “)”, “[", "]“, “{“, ”}”,這三個括號可以按照任意的次序嵌套使用。

輸入

有多個表達式,輸入數據的第一行是表達式的數目,每個表達式占一行。

輸出

對每個表達式,若其中的括號是匹配的,則輸出”yes”,否則輸出”no”。

樣例輸入

4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9

樣例輸出

yes no no no 解題思路: 加入括號一一配對,則()[] {}左右符號一一對應,也就是說在字符串中間必有一左一右括號相連並且兩者對應,說先應該去掉除括號以外的其他字符,然後運用棧依次將左括號存入棧中,遇到右括號時間與棧底符號比較,匹配時間棧的標記元素減一。直到最後若棧的標記元素等零,說明棧中的括號一一匹配。 代碼 #include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct stu{
char s[1010];
int head;
int tail;
}st;
int funz(char s)
{
if(s==‘(‘)
return 1;
else if(s==‘[‘)
return 2;
else if(s==‘{‘)
return 3;
else
return -1;
}
int funy(char s)
{
if(s==‘)‘)
return 1;
else if(s==‘]‘)
return 2;
else if(s==‘}‘)
return 3;
else
return 0;
}
int main()
{
int i,m,n;
st s1;
char s0;
char s[1010];
scanf("%d",&m);
getchar();
while(m--)
{
s1.head=s1.tail=0;
i=0;
while(scanf("%c",&s0),s0!=‘\n‘)
if(s0==‘(‘||s0==‘)‘||s0==‘[‘||s0==‘]‘||s0==‘{‘||s0==‘}‘)
s[i++]=s0;
s[i]=‘\0‘;
if(strlen(s)%2!=0)
{
printf("no\n");
continue;
}
for(i=0;s[i]!=‘\0‘;i++)
{
if(s[i]==‘(‘||s[i]==‘[‘||s[i]==‘{‘)
s1.s[s1.tail++]=s[i];
else if(s[i]==‘)‘||s[i]==‘]‘||s[i]==‘}‘)
{
if(funz(s1.s[s1.tail-1])==funy(s[i]))
s1.tail--;
}
}
if(s1.tail==0)
printf("yes\n");
else
printf("no\n");
}
return 0;
}

數據結構 棧的應用