1354:括弧匹配检验
时间限制: 1000 ms 内存限制: 65536 KB
【题目描述】
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,如([ ]())或[([ ][ ])]等为正确的匹配,[( ])或([ ]( )或 ( ( ) ) )均为错误的匹配。
现在的问题是,要求检验一个给定表达式中的括弧是否正确匹配?
输入一个只包含圆括号和方括号的字符串,判断字符串中的括号是否匹配,匹配就输出 “OK” ,不匹配就输出“Wrong”。输入一个字符串:[([][])],输出:OK。
【输入】
输入仅一行字符(字符个数小于255)。
【输出】
匹配就输出 “OK” ,不匹配就输出“Wrong”。
【输入样例】
[(])
【输出样例】
Wrong
1. #include <iostream> 2. #include <cstdio> 3. #include <cstring> 4. #include <stack> 5. using namespace std; 6. stack<char> s; 7. char ch[260]; 8. int main(int argc, char *argv[]) 9. { 10. gets(ch); 11. int l=strlen(ch); 12. for(int i=0;i<l;i++){ 13. if(ch[i]=='(') s.push('('); 14. else if(ch[i]=='[') s.push('['); 15. else if(ch[i]==')'){ 16. if(s.empty()){cout<<"Wrong"<<endl;return 0;} 17. else if(s.top()=='(') s.pop(); 18. else {cout<<"Wrong"<<endl;return 0;} 19. } 20. else if(ch[i]==']'){ 21. if(s.empty()){cout<<"Wrong"<<endl;return 0;} 22. else if(s.top()=='[') s.pop(); 23. else {cout<<"Wrong"<<endl;return 0;} 24. } 25. } 26. if(!s.empty()) cout<<"Wrong"<<endl; 27. else cout<<"OK"<<endl; 28. return 0; 29. }
1. #include <iostream> 2. #include <cstdio> 3. #include <stack> 4. using namespace std; 5. int main(int argc, char *argv[]) 6. { 7. stack<char> stk; 8. char exp[260]={0}; 9. gets(exp); 10. int i=0; 11. while(exp[i]!='\0'){ 12. if(exp[i]=='('||exp[i]=='[') 13. stk.push(exp[i]); 14. else if(exp[i]==')'||exp[i]==']') 15. { 16. if(stk.size()) { 17. if((exp[i]==')'&& stk.top()=='(')||(exp[i]==']' && stk.top()=='[')) stk.pop(); 18. else { 19. cout<<"Wrong"<<endl; 20. return 0; 21. } 22. } 23. else { 24. cout<<"Wrong"<<endl; 25. return 0; 26. } 27. } 28. i++; 29. } 30. if(!stk.size()) cout<<"OK"<<endl; 31. else cout<<"Wrong"<<endl; 32. return 0; 33. }