我需要檢查字母「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