2017-03-01 30 views
-1

我需要检查字母“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'

+1

嗯,这看起来错了'C == s.pop(三)' – SingerOfTheFall

回答

2

您需要一种方法来看待堆栈顶部的电流值不弹出它:

class stack { 
    ... 
    int top() { // never use on an empty stack 
     return body[ptr-1]; 
    } 
    ... 
}; 

这样你可以这样写:

for (int c : str) { 
    // short circuit evaluation ensures that top is never called on an empty stack 
    if (s.empty() || (c == s.top()) { 
     s.push(c); 
    } 
    else { 
     s.pop(&c); 
    } 

如果y OU不能,你必须,如果它不应该被弹出推回弹出的值:

for (int c : str) { 
    int d; 
    if (! s.pop(&d)) { // s was empty 
     s.push(c); 
    } 
    else if (c == d) { 
     s.push(d);  // should not have been popped 
     s.push(c);  
    } 
} 
0

你可以每次看到a

for (int c = 0; c < str.size() ; ++c) { 
    if (str[c] == 'a') s.push('a'); 
} 
if ((s.size() * 2) == str.size()) cout << "YES\n"; else cout << "NO\n"; 

堆栈大小::可以实现这种方式:

int stack::size() { 
    return ptr; 
} 
+0

@SergeBallesta你是正确的。我会编辑我的答案 – Rishi

+0

我认为我的逻辑会更好。我们需要比较当前的字母和堆栈中的字母 –

+0

现在abbb回答是! –

相关问题