Description
设计一个动态字符堆栈类,要求堆栈可存储的字符数量可动态扩展,在构造函数中使用new进行初始堆栈空间内存分配,在析构函数中采用delete释放内存,堆栈类框架如下所示:
class CStack
{
char *s;
int tp;
int size;
public:
CStack(int initSize = 5);
~CStack();
bool isEmpty();
bool isFull();
void push(char c);
char pop();
char top();
};
编码完善上述动态字符堆栈类,基于此堆栈类,判断一个字符串中的括号是否正确匹配。如输入"{[(1+2)/(3+4)*5-3]*2}/3-4",则字符串中的括号匹配,若输入"[(])",则字符串中的括号不匹配。
Input
采用getline(cin, string)读入一个可能包含"()[]{}"三种括号的字符串。
Output
判断输入字符串中的括号是否正确匹配,若正确匹配,输出"Balanced",否则输出"Not balanced"。
Sample Input 1
{[9+(3-1)*3+10]-5}/2
Sample Output 1
Balanced
Sample Input 2
int main(){int a;cin >> a; if (a==0)cout << "Hello world!" << endl;else cout << "Hello China!" << endl;
Sample Output 2
Not balanced
**************************************************************************************************************
代码实现
#include <iostream>
#include <string>
class CStack {
char* s;
int tp;
int size;
public:
CStack(int initSize = 5) : tp(-1), size(initSize) {
s = new char[initSize];
}
~CStack() {
delete[] s;
}
bool isEmpty() {
return tp == -1;
}
bool isFull() {
return tp == size - 1;
}
void push(char c) {
if (isFull()) {
char* newS = new char[size * 2];
for (int i = 0; i <= tp; ++i) {
newS[i] = s[i];
}
delete[] s;
s = newS;
size *= 2;
}
s[++tp] = c;
}
char pop() {
if (isEmpty()) {
return '\0';
}
return s[tp--];
}
char top() {
if (isEmpty()) {
return '\0';
}
return s[tp];
}
};
std::string isBalanced(const std::string& s) {
CStack stack;
std::string openBrackets = "([{";
std::string closeBrackets = ")]}";
for (char c : s) {
if (openBrackets.find(c) != std::string::npos) {
stack.push(c);
} else if (closeBrackets.find(c) != std::string::npos) {
if (stack.isEmpty()) {
return "Not balanced";
}
char lastOpenBracket = stack.pop();
if (openBrackets.find(lastOpenBracket) != closeBrackets.find(c)) {
return "Not balanced";
}
}
}
return stack.isEmpty() ? "Balanced" : "Not balanced";
}
int main() {
std::string input;
std::getline(std::cin, input);
std::cout << isBalanced(input) << std::endl;
return 0;
}