题目要求:
从键盘读入一个字符串,其中只含有() {} [ ] ,判断该字符串中的每种括号是否成对出现。
提示:可借助栈来实现,括号必须配对出现,如()[ ]{},这是匹配的括号,如([{])},这是不匹配的括号(中间无空格)。
输入描述
输入一个字符串(中间不包含空格)
输出描述
匹配输出yes,否则输出no
输入样例
(([{}]))
输出样例
yes
解题思路: 使用栈可以很巧妙的解决这个问题。遍历字符串,若字符为左括号,则将这个字符入栈,若为右括号,则从栈里弹出一个字符,判断弹出的这个字符是否为对应的左括号,若是,则继续遍历,若不是,则括号不匹配,退出循环,返回判断结果。循环结束后,根据判断结果输出 yes 或者 no。
通关代码:
#include <iostream>
#define MaxSize 100
using namespace std;
class Matcher {
public:
Matcher();
public:
void Push(char ch);
char Pop();
bool isEmpty();
bool Match(string str);
private:
char arr_[MaxSize];
int top_;
};
Matcher::Matcher() {
top_ = -1;
}
void Matcher::Push(char ch) {
if (top_ == MaxSize) throw "上溢";
arr_[++top_] = ch;
}
char Matcher::Pop() {
if (top_ < 0) throw "None";
char res = arr_[top_];
top_--;
return res;
}
bool Matcher::isEmpty() {
return top_ < 0 ? true : false;
}
bool Matcher::Match(string str) {
int LEN = str.size();
bool isMatch = true;
for (int i = 0; i < LEN; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
Push(str[i]);
} else {
if (str[i] == ')') {
if (isEmpty() || Pop() != '(') {
isMatch = false;
break;
}
} else if (str[i] == ']') {
if (isEmpty() || Pop() != '[') {
isMatch = false;
break;
}
} else if (str[i] = '}') {
if (isEmpty() || Pop() != '{') {
isMatch = false;
break;
}
}
}
}
return isMatch;
}
int main() {
Matcher m;
string str;
cin >> str;
cout << (m.Match(str) ? "yes" : "no");
return 0;
}
毕。