我需要检查字母“a”的数量是否等于使用堆栈的字母数量“b” 。 所以我理解这个任务的逻辑,但我的代码不起作用。C++:如何检查使用堆栈的字符串中是否存在相同数量的字母'a'和'b'
逻辑:
如果当前信==在堆栈信(s.pop())或堆栈为空,则推入堆栈 从栈 其他弹出堆栈的周期检查尺寸的结束之后。如果是空的,所以字母数为equl,否则不
我已经有ABAB,AABB,AB类栈
#include <string>
#include <iostream>
#include <cstdlib> // для system
using namespace std;
class stack {
public:
stack() {
ptr = 0;
}
~stack() {}
bool push(int val) {
if (ptr >= MAXSIZE) return false;
body[ptr++] = val; return true;
}
bool pop(int *val) {
if (ptr == 0) return false;
*val = body[--ptr]; return true;
}
bool empty() {
return ptr == 0;
}
private:
enum { MAXSIZE = 100 };
int body[MAXSIZE];
int ptr; // указатель на последний элемент
};
int main()
{
stack s;
std::string str;
std::cout << "Enter your ab string ";
getline(std::cin, str);
for (int c : str) {
if (c == s.pop(&c) || s.empty()) {
s.push(c);
}
else {
s.pop(&c);
}
}
if (s.empty()) {
cout << "YES\n";
system("pause");
return 0;
}
else {
cout << "NO\n";
system("pause");
}
}
结果 '是' 了AAABB,ABA 'NO'
嗯,这看起来错了'C == s.pop(三)' – SingerOfTheFall