潇潇_暮雨
2018-11-20 20:01
学了标准模板库,就该用标准模板库解决问题
#include<iostream>
#include<string>
#include<stack>
using namespace std;
char judge(char c)
{
char cneed;
switch(c)
{
case '{':cneed='}';break;
case '[':cneed=']';break;
case '(':cneed=')';break;
}
return cneed;
}
int main()
{
stack<char> s;
string brackets;
cin>>brackets;
for(int i=0;i<brackets.size();i++)
{
if(s.empty())
{
s.push(brackets[i]);
continue;
}
judge(s.top())==brackets[i]?s.pop():s.push(brackets[i]);
}
s.empty()? cout<<"匹配":cout<<"不匹配";
return 0;
}
还有更好的写法吗?
// myself void bracketMatch1(const char* str) { MyStack<char>* pMatch = new MyStack<char>(30); char currentNeed = 0; for (int i = 0; i < strlen(str); i++) { if (str[i] == currentNeed) { if (pMatch->pop(currentNeed) == 0) currentNeed = 0; // 1. 通过pMatch更新当前待匹配括号 // 2. pMatch为空时,需给当前待匹配括号置零 } else { if (currentNeed != 0) pMatch->push(currentNeed); currentNeed = str[i] == '(' ? ')' : (str[i] == '[' ? ']' : 'k'); } } pMatch->stackEmpty()&¤tNeed==0 ? cout << "Yes" << endl : cout << "No" << endl; delete pMatch; pMatch = nullptr;}
非常好,再加上空格等非括号判断就完美了
#include <iostream>#include <stdlib.h>#include "stack.h"#include "coordinate.h"using namespace std;//函数声明bool BrackerMatch(char *str);//主函数int main(){ /* 栈应用--括号匹配 描述:任意输入一组括号,判断括号是否匹配 */ char str[]= "([]})"; if (BrackerMatch(str)) { cout << "括号成功匹配" << endl; } else { cout << "括号不匹配" << endl; } system("pause"); return 0;}bool BrackerMatch(char *str) { MyStack<char> *p = new MyStack<char>(30); char e = 0; for (int i = 0; i < strlen(str); i++) { switch(str[i]) { case '(': p->push(str[i]); p->stackTraverse(false); break; case '[': p->push(str[i]); break; case '{': p->push(str[i]); break; case ')': if (p->getTopElement()!='(') { cout << p->getTopElement() << endl; return false; } else { p->pop(e); break; } case ']': if (p->getTopElement() != '[') { return false; } else { p->pop(e); break; } case '}': if (p->getTopElement() != '}') { return false; } else { p->pop(e); break; } default: break; } } return p->stackEmpty();}
数据结构探险—栈篇
62733 学习 · 102 问题
相似问题