2017-03-01 56 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回答是! –

相關問題