Match a simple balanced language I apologise if the title is not very descriptive. If someone can recommend a clearer one I'll edit it. I have an exercise question as:


  The language L={anbn} where n ≥ 1, is a language of all words with
  the following properties:
  
  
  The words consist of strings of a’s followed by b’s.
  The number of b’s is equal the number of a’s. 
  Examples of words that belong to L are:
  
  
  ab, where n=1;
  
  aabb, where n=2;
  
  aaabbb, where n=3;
  
  aaaabbbb, where n=4.
  
  One way to test if a word w belong to this language L is to use a
  stack to check if the number of a’s balances the number of b’s. Use
  the following header and write a function isInLanguageL2 that
  uses a stack to test if any word belongs to L. If w belongs to L
  then the isInLanguageL2 should return true otherwise
  isInLanguageL2 should return false.
  
  bool isInLanguageL(string w);
  
  Note the following:
  
  
  Only words belonging to L should be accepted.
  The word bbaa does not belong to L.
  Do not count the number of a’s or b’s.
  


I've written the following code which solves the problem. 

bool isInLanguageL2(string w){

    linkedStackType&lt;string&gt; wordStack;

    int size = w.length();
    int a = 0;
    int b = 0;

    if(size % 2 != 0)   //word length must be an equal number
        return false;
    else{
        //read first half of word
        for(int i = 0; i &lt; size/2; i++){    //check if the first half consists of A's
            if(w[i] != 'a' &amp;&amp; w[i] != 'A')
                return false;
            else
                wordStack.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid
        }

        //read second half of word
        for(int i = size/2; i &lt; size; i++){     //check if the second half consists of B's
            if(w[i] != 'b' &amp;&amp; w[i] != 'B')
                return false;
            else
                wordStack.push(string(1, w[i]));    //convert char to string and push to stack if the letter is valid
        }
    }

    //check number of A's and B's in the stack
    while(!wordStack.isEmptyStack()){
        if(wordStack.top() == "b" || wordStack.top() == "B"){
            b++;
            wordStack.pop();
        }
        else{
            a++;
            wordStack.pop();
        }
    }

    //check if number of B's is equal to number of A's
    if(b==a)
        return true;

}


However, since the question says "Do not count the number of a’s or b’s.", I've instead created two stacks and just compared their lengths. Is there a way to do this using a single stack since the question mentions using a stack without explicitly counting the A's and B's to test the word.

bool isInLanguageL2(string w){

    linkedStackType&lt;string&gt; wordStackA, wordStackB;

    int size = w.length();
    int a = 0;
    int b = 0;

    if(size % 2 != 0)   //word length must be an equal number
        return false;
    else{
        //read first half of word
        for(int i = 0; i &lt; size/2; i++){    //check if the first half consists of A's
            if(w[i] != 'a' &amp;&amp; w[i] != 'A')
                return false;
            else
                wordStackA.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid
        }

        //read second half of word
        for(int i = size/2; i &lt; size; i++){     //check if the second half consists of B's
            if(w[i] != 'b' &amp;&amp; w[i] != 'B')
                return false;
            else
                wordStackB.push(string(1, w[i]));    //convert char to string and push to stack if the letter is valid
        }
    }

    //check if number of B's is equal to number of A's
    if(wordStackA.length() == wordStackB.length());
        return true;

}


Also, I have a follow up to this question. A sort of extension. Should I add it here or create a new question for it as it might make this question rather long.
This exercise is somewhat unsettling. On the one hand, a stack, as part of a pushdown automaton, is the canonical way to decide balanced languages such as this one; on the other hand, there are much more efficient, idiomatic and practical ways to solve that particular exercise. It is unclear whether it's a computer science exercise or a language learning exercise, one to make concepts sink in or one to discover C++'s expressiveness.

A stack would have been more easily justified if the function argument had been a std::istream&amp; for instance, since it can be traversed only once; or if starting / ending tags had come of different kinds (if they're all the same an integer makes for a perfect stack and counting shouldn't be discriminated).

As @Mike Borland said, the trick to answer that question is to avoid explicit counting by popping the stack filled with as while you iterate over the rest of the string. Something along the lines:

#include &lt;stack&gt;
#include &lt;string&gt;

bool is_ab_balanced(const std::string&amp; str) {
    if (!str.size()) return false; 
    auto it = str.begin();
    std::stack&lt;char&gt; as;
    while (it != str.end() &amp;&amp; *it == 'a') as.push(*it++);
    while (!as.empty()) {
        if (it == str.end() || *it != 'b') return false;
        as.pop(); ++it;
    }
    return it == str.end();
}


By the way, you'll notice that:


it always is better to use standardized containers unless you need customized behavior: std::stack is certainly better optimized and tested than linkedStackType&lt;&gt;
you shouldn't take a string by value as an argument, unless you intend to modify it while keeping the original string unchanged. Here, there's no modification, so use a const reference instead.
you should get rid of unused variables (see a and b in your second version). Those superfluous variables probably are a by-product of bad habits: declaring variables too far ahead of their use, and not enabling all warnings when you compile your code.
iterators are a better way to iterate over a range: it's more idiomatic, it's necessary to leverage the power of the STL, and it also avoids that extra size variable.
A few more key-strokes are better than using namespace std, which is is a bad idea


But, as I said, a good exercise should look more like real life. In real life, you use a stack only if it is the best way to go. So how would you check if a string belongs to the language if you could choose without restriction?

My take on that would be:

#include &lt;string&gt;
#include &lt;algorithm&gt;

using Iterator = std::string::iterator;
bool is_balanced(Iterator first, Iterator last) {
    auto middle = std::next(first, std::distance(first, last) / 2);
    return std::equal(first, middle, middle, last, [](auto a, auto b) {
        return a == 'a' &amp;&amp; b == 'b';
    });
}


Or, other more meaningful exercises would have been:


how would you check if parenthesis are balanced in an expression (I wouldn't use a stack here either)?
how would you check if html tags are correctly balanced (here using a stack is meaningful)?