这个代码是我在学习编程风格之前写的代码,改变之后的我后续会整体发上去。
//括号匹配 #include<iostream> #include<stack> using namespace std; int iskh(char ch) { if (ch == ‘(‘ || ch == ‘[‘ || ch == ‘{‘)return 1; else if (ch == ‘)‘ || ch == ‘]‘ || ch == ‘}‘)return -1; else return 0; } int matching() { stack<char> S; char ch,temp; int i; while ((ch = getchar()) != ‘\n‘) { //判断是否为括号 i = iskh(ch); if (i > 0)//是左括号,入栈 S.push( ch); else if (i < 0)//是右括号,取栈顶判断是否匹配 { if (S.empty()) return 0; temp = S.top(); if ((temp == ‘(‘ && ch == ‘)‘)|| (temp == ‘[‘ && ch == ‘]‘)|| (temp == ‘{‘ && ch == ‘}‘))//匹配成功 S.pop(); else//匹配失败 return 0; } else//不是括号,不执行任何操作,继续往下遍历 continue; } return 1; } int main(){ int i = matching(); if (i) cout << "匹配成功!" << endl; else cout<<"匹配失败!"<<endl; return 0; }
原文地址:https://www.cnblogs.com/lyf98/p/11706758.html
时间: 2024-11-08 22:36:24