【大風】matrix:valid parentheses括號匹配程式碼分享
阿新 • • 發佈:2019-01-29
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
#include <stdio.h>
#include <string.h>
//資料結構:棧
//演算法:抓取到左括號,就將它推入棧(push);抓取到右括號,就pop,取出一個左括號,判斷是否匹配,如果匹配則繼續;不匹配立即結束迴圈,輸出false。
int stack[1000];
int len_stack;
int pop(void)
{
//自己想
}
void push(int new_element)
{
//自己想
}
int trans(char c)//把括號轉化為數字來處理
{
switch (c)
{
case '{':return 1;
case '}':return 2;
case '[':return 3;
case ']':return 4;
case '(':return 5;
case ')' :return 6;
}
}
int main()
{
char exp[10000];
scanf("%s",&exp);
long len_exp =strlen(exp);
int boo=1;//boo為1代表匹配,為0代表不匹配
int t,i;
len_stack=0;
for (i=0;i<len_exp;i++)
{
t=trans(exp[i]);
if (t%2==0)
{
if (len_stack==0) //如果棧中沒了元素,說明右括號前面沒有左括號,
{
boo=0;
break;
}
else
{
if (pop()+1!=t)
{
boo=0;
break;
}
}
}
else push(t);
}
if (len_stack!=0) boo=0;
if (boo==0) printf("False\n");
else printf("True\n");
}