检查一段C语言代码的小括号( )、 中括号 [ ] 和大括号{ } 是否匹配。
,(),[],{}
将这段代码存入以字符串中,遍历字符串,分两种情况
1.,遇到'/'并且栈顶元素不等于'/'时,将其入栈,初始情况栈为空,遇到‘*’同理,
再次遇到这些符号时则栈顶元素出栈
2.'()','[]','{}',这三种符号,只需要在遇到'(','[''{'时入栈,遇到')',']','}'时将栈顶元素出栈
遍历完后判断栈是否为空,若为空则符号匹配,否则不匹配
代码
#include#include #include using namespace std; const int maxn = 1010; typedef struct node { char data[maxn]; int top; } * link; void Init(link stk) { stk -> top = 0; } void Push_stk(link stk , int x) { stk -> data[++stk -> top]= x; } void Pop_stk(link stk) { stk -> top--; } int GetTop(link stk) { return stk -> data[stk -> top]; } int Getsize(link stk) { return stk -> top; } int Empty_stk(link stk) { return !Getsize(stk); } int main() { link stk = (link) malloc (sizeof(node)); Init(stk); string s; cin >> s; int len = s.length(); for(int i = 0 ; i < len ; i++) { if(s[i] != ',') { if(s[i] == '(') Push_stk(stk , s[i]); if(s[i] == ')') Pop_stk(stk); if(s[i] == '/' && GetTop(stk) != '/') Push_stk(stk , s[i]); if(s[i] == '*' && GetTop(stk) != '*') Push_stk(stk , s[i]); if(s[i] == '[') Push_stk(stk , s[i]); if(s[i] == '{') Push_stk(stk , s[i]); if(s[i] == '}') Pop_stk(stk); if(s[i] == ']') Pop_stk(stk); if(s[i] == '*' && GetTop(stk) == '*') Pop_stk(stk); if(s[i] == '/' && GetTop(stk) == '/') Pop_stk(stk); if(s[i] == ')') Pop_stk(stk); } } if(!Empty_stk(stk)) cout << "true"; else cout << "false"; return 0; }



