Balancing Symbols"/>
Balancing Symbols
symbols匹配问题
#include<iostream>
#include<string>
using namespace std;struct Node
{char data;Node*next;
};struct LinkStack
{Node*top;
};LinkStack*create()
{LinkStack*stack = new LinkStack;stack->top = NULL;return stack;
}bool isEmpty(LinkStack*stack)
{return (stack->top == NULL);
}void pop(LinkStack*stack)
{Node*p = stack->top;stack->top = stack->top->next;delete p;
}void push(LinkStack*stack, char item)
{Node*p = new Node;p->data = item;p->next = stack->top;stack->top = p;
}char Top(LinkStack*stack)
{return stack->top->data;
}int main()
{int n;cin >> n;while (n-->0){string s;cin >> s;LinkStack*stack = create();bool flag = true;int n = s.size();for (int i = 0; i < n; i++){if (s[i] == '(' || s[i] == '[' || s[i] == '{')push(stack, s[i]);if (s[i] == ')'){if (!isEmpty(stack)){if (isEmpty(stack) && Top(stack) != '('){flag = false;break;}else{pop(stack);}}else{flag = false;break;}}else if (s[i] == ']'){if (!isEmpty(stack)){if (Top(stack) != '['){flag = false;break;}else{pop(stack);}}else{flag = false;break;}}else if (s[i] == '}'){if (!isEmpty(stack)){if (Top(stack) != '{'){flag = false;break;}else{pop(stack);}}else{flag = false;break;}}}if (!isEmpty(stack))flag = false;if (flag)cout << "Yes" << endl;if (!flag)cout << "No" << endl;delete stack;}return 0;
}
转载于:.html
更多推荐
Balancing Symbols
发布评论