Search code examples
c++stringpalindrome

Palindrome excluding special characters and spaces


I have written a code for checking if a string is palindrome or not which should exclude white spaces and special characters and should be case in-sensitive. So the function isPalindrome(string A) takes in a string and returns 1 if its a palindrome and 0 if its not.

For example: input: A man, a plan, a canal: Panama output: 1 Below is the code-

int isPalindrome(string A) {
    string::iterator it;
    string::reverse_iterator rit;
    it=A.begin();
    rit=A.rbegin();
    while(it!=A.end() && rit!=A.rend()){
        while(!isalnum(*rit))       //if char from the end is not alphanumeric, then increment the reverse iterator till we find the alphanumeric char. 
            ++rit;
        while(!isalnum(*it))       //if char from the start is not alphanumeric, then increment the iterator till we find the alphanumeric char. 
            ++it;
        if(tolower(*it)!=tolower(*rit))  //case in-sensitive comparison
            return 0;
        ++it;
        ++rit;
    }
    return 1;
}

It works well for all the variations of input like A man, a plan, a canal: Panama" or "A man, a plan, a canal: Panama but when I input "A man, a plan, a canal: Panama" it fails with run time error.

So please let me know where am I going wrong?


Solution

  • The problem was that both iterators might have reached the end in the nested while loops, there should be checking for this.

    int isPalindrome(string A) {
        string::iterator it;
        string::reverse_iterator rit;
        it=A.begin();
        rit=A.rbegin();
        while(it!=A.end() && rit!=A.rend()){
            while(rit != A.rend() && !isalnum(*rit))       //if char from the end is not alphanumeric, then increment the reverse iterator till we find the alphanumeric char. 
                ++rit;
            while(it != A.end() && !isalnum(*it))       //if char from the start is not alphanumeric, then increment the iterator till we find the alphanumeric char. 
                ++it;
    
            if (it == A.end() || rit == A.rend())
                break;
    
            if(tolower(*it)!=tolower(*rit))  //case in-sensitive comparison
                return 0;
            ++it;
            ++rit;
        }
        return 1;
    }