Home > Software engineering >  Check if a string contains palindromes separated by a hash symbol using a vector as an implementatio
Check if a string contains palindromes separated by a hash symbol using a vector as an implementatio

Time:02-21

I have to write a bool mirrored() function that has to return true if the input meets the following criteria.

The string is mirrored if it contains palindrome substrings separated by one (and only one) hash symbol, and if all the palindromes are correct.

So it should return true for the following:

#, ####, abc#cba, ##a#aabc#cba

and false for the following:

abc, abc#cv, abc#cbaa#aa, ab#bac##c

This is my first exercise concerning the use of stack-related functions and I'm having difficulties with the following code:

bool isMirrored(){
    vector<char> stack;
    char s;
    bool hashSymbol = false;
    while(cin >> s){
        if(s=='#'){
            hashSymbol = true;
            while(hashSymbol && !stack.empty()){
                if(s==stack.back()){
                    stack.pop_back();
                }
                if(stack.empty()){
                    hashSymbol=false;
                }
                else{
                    return false;
                }
            }
        }
        stack.push_back(s);
    }
    return true;
}

My plan is when a # is not present, it loads the stack with characters and when a # is found, my algorithm goes into "check mode" (hence switching the hashSymbol variable to true) and checks if the topmost element of the stack is equal to the next character. If it is, then it checks for the next one and drops the topmost element of the stack. If the characters don't match, then the function returns false. When the stack is empty, then the algorithm should go into "input mode" again (hashSymbol switched to false) and the cycle begins anew. If the function didn't return false and the input is over, then it must return true.

My problem with this is that I can't figure out how to move to the next character in the input. When it finds a #, it enters the inner while statement while s is still the # character.

I thought of (at first glance at least) another possible much simpler solution, but I still can't figure out how to move to the next character in the input when a # is found.

vector<char> stack;
char s;
while(cin >> s){
    if(s!='#'){
        stack.push_back(s);
    }
    else{
        if(!stack.empty()){
            [this is where I would check for equal characters]
        }
        else{
            return true;
        }
    }
}

return stack.empty();

CodePudding user response:

A few hints for the first version.

The

while(hashSymbol && !stack.empty()){

Is superfluous. Check just one character at a time.

stack.push_back(s);

pushes the '#' on the stack too.

I think you will have an easier time to adapt your second version rather than correcting the first.

Your not far away from a solution..

  • Related