user13631407
user13631407

Reputation:

Palindrome program not returning correct answers

I am currently coding in C++ and am wanting only take notice of lowercase letters and numbers.

My problem is that when I enter a string containing integers and characters (such as a lowercase letter), does not return the correct answer for and ODD length (of the array) above the value of 3.

For instance, if I was to enter '1b1', it would return as a palindrome, otherwise if I were to write '1bbb1', it would return false.

Here is the code:

bool isPalindrome(string s){
int len = s.size();
int mid = len / 2;
int unsigned i;

stack<char> palindromeStack;

for (i = 0; i < mid; i++)
{
    if(s[i] <= 47 && s[i] >= 58 ||
    s[i] <= 96 && s[i] >= 123){
        s.erase(i,1);
        i--;
        
    }

    if (s[i] > 47 && s[i] < 58 ||
    s[i] > 96 && s[i] < 123)
    {
        palindromeStack.push(s[i]);
    }

    if (len % 2 != 0)
    {
        i++;
    }
}

while (s[i] != '\0')
{
    char ele;
    ele = palindromeStack.top();
    palindromeStack.pop();

    if (ele != s[i])
    {
        return false;
        i++;
    }
    return true;
}}

I assume this has something to do with the IF statements in relation to the length of the array, but since I'm still quite new to programming, I am unable to find the solution.

Any help would be greatly appreciated! (this includes directing me to already answered questions that will solve my issue)

P.S. Code brackets were slightly modified to fit within the Stack Overflow Code Sample function.

Thanks

Upvotes: 0

Views: 136

Answers (2)

Pepijn Kramer
Pepijn Kramer

Reputation: 12848

This code will bail out checking at first sign of a mismatch :

#include <cassert>
#include <string>

bool is_palindrome(const std::string& str)
{
    for (int front = 0, back = static_cast<int>(str.length()) - 1; front < back; ++front, --back)
    {
        if (str[front] != str[back]) return false;
    }
    return true;
}

int main()
{
    assert(is_palindrome(""));
    assert(is_palindrome("1"));
    assert(is_palindrome("121"));
    assert(is_palindrome("abcdefedcba"));
    assert(!is_palindrome("121abc"));
    return 0;
}

Edit (now with iterator & reverse iterator):

bool is_palindrome(const std::string& str)
{
    for (auto [front, back] = std::tuple{str.begin(), str.rbegin()}; front < back.base(); ++front, ++back)
    {
        if (*front != *back) return false;
    }
    return true;
}

Upvotes: 0

TUSHAR TRIPATHI
TUSHAR TRIPATHI

Reputation: 28

I have a much better code. Usage of any data structure template does not indicate that it is a good code. If your target is to check if a string is palindrome including alphanumeric characters please refer to the following code. I have shared the screenshots as an example :-

    #include <iostream>
    #include<string>
    using namespace std;

string transform(string s)
{
    string result = "";
    for(char ch : s)
    {
        if(('a'<=ch && ch<='z') || ('0'<=ch && ch<='9') )
        result += ch;
    }
    return result;
}
    
    int main() {

        string s="";
        
        // reading the input from the std input
        cin>>s;
        s = transform(s);
        bool isPalindrome = true;
        for(int i = 0, j = s.size()-1; i<=j; i++,j--)
        {
            if(s[i]!=s[j])
            {
                isPalindrome = false;
                break;
            }
        }
        if(isPalindrome)
        {
            cout<<"Palindrome";
        }
        else
        {
            cout<<"Not Palindrome";
        }
        return 0;
    }

The key point is it won't be a palindrome if the values are not same from both ends of the string. If any character is unequal it is proven that it is not a palindrome, hence we need not to go for other comparisons. This has lesser lines of code and works in every scenario.enter image description here

enter image description here

Upvotes: 0

Related Questions